An implementation of Visual Basic that is built into Microsoft products.
The macro structure is valid. To make it function reliably, ensure that:
- A document is open and the text you want to change is in that document.
- The selection is in the main story (not in a header, footer, or another pane) before running the macro.
- The Find is fully initialized before each Execute, including clearing previous settings.
A more robust version based on the documented Find/Replacement pattern is:
Sub Rename_Trainers()
Dim FindArray As Variant
Dim ReplArray As Variant
Dim i As Long
FindArray = Array("RICHARDSON NORV", "D & B WEATHERLE", "THURLOW O'MALLE", "WALKER BERGERSO", "O'SULLIVAN SCOT")
ReplArray = Array("RICHARDSON NORVALL", "D & B WEATHERLEY", "THURLOW O'MALLEY", "WALKER BERGERSON", "O'SULLIVAN SCOTT")
Options.DefaultHighlightColorIndex = wdNoHighlight
For i = LBound(FindArray) To UBound(FindArray)
With ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = FindArray(i)
.Replacement.Text = ReplArray(i)
.Replacement.Font.Color = wdColorBlue
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
Next i
End Sub
Key changes:
- Uses
ActiveDocument.Content.Findso the whole document is searched, independent of the current selection. - Calls
.ClearFormattingon bothFindandReplacementbefore each run, as shown in the documentation. - Uses
Wrap:=wdFindContinueso all occurrences in the document are processed.
If the original code must use Selection.Find, adapt the documented pattern:
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
'... set Text, Replacement.Text, options ...
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
End With
This ensures previous Find settings do not prevent matches and that all instances are replaced.
References: