I've recorded a macro to, find a specific search term "INCLUDETEXT" in a large document, highlight the text associated with that search term, convert the highlighted text to a field code, and then update the new field code.
I need to loop the macro until the "INCLUDETEXT" term is not found.
I've tried to repeat the code 50 times, but ended up with odd nested field codes on the last instance of the "INCLUDETEXT" term.
Sub InsertFields()
'
' InsertFields Macro
' Inserts field codes associated with an "INCLUDETEXT" link.
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "INCLUDETEXT"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
PreserveFormatting:=False
Selection.Fields.Update
End Sub
The macro works on each single instance of the search term. I would like to find and update all "INCLUDETEXT" terms.
I have looked at Repeating Microsoft Word VBA until no search results found, but could not figure out how to adapt my macro to fit.
My failed attempt at a "Do If" loop. I believe the specific error was an "End If" without an "If":
Sub InsertFields()
'
' InsertFields Macro
' Inserts all fields associated with an "INCLUDETEXT" link.
' Selection.Find.ClearFormatting
With Selection.Find
.Text = "INCLUDETEXT"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Found = True
Selection.Find.Execute
If Selection.Find.Found Then
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
PreserveFormatting:=False
Selection.Fields.Update
End If
Loop
End Sub
Selection.Find.Execute
is needed before theDo While
line, otherwise this will evaluate toFalse
so the loop won't run; and then putSelection.Find.Execute
just before theLoop
line. OR put the evaluation at the end of the loop (Loop While Selection.Find.Found
). Then you should no longer need theIf...End If
lines – Cindy Meister