An implementation of Visual Basic that is built into Microsoft products.
Hi @SteveD .
You’re close, but a couple Word-VBA wildcard details are off:
-
\3refers to the 3rd capture group. You only have one group, so you want\1. - If your goal is to prefix any 3-digit number with three zeros (e.g.,
123→000123), use000\1. - Also, your current code only replaces the first match. Use
wdReplaceAllto replace all matches in the selection.
Sub AddZeroBeforeThreeDigits()
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
' Find any 3-digit number
.Text = "([0-9]{3})"
' Prefix the match with three zeros
.Replacement.Text = "000\1"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
' Replace all occurrences
.Execute Replace:=wdReplaceAll
End With
End Sub
If you actually meant “replace the 3 digits with 000” (so 123 becomes 000), then just set:
.Replacement.Text = "000".
Here's the result with the macro text above:
Before:
After
If you found my response helpful or informative, I would greatly appreciate it if you could follow this guidance or provide feedback.
Thank you.