Lukenn77
Lukenn77

Reputation: 19

Find text and format

I have recorded a macro in Word 2007 that finds a word, moves the cursor two lines up, inserts three '***', then highlights the line. It works on the first instance of the found word. I am struggling to get it to repeat throughout the document with all instances of the word I want it to find.

This is the output from my recorded macro. I need the actions to be repeated for each instance of "B,".

 Sub HighlightNewItems()
'
' HighlightNewItems Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "B,"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.MoveUp Unit:=wdLine, Count:=2
    Selection.MoveLeft Unit:=wdWord, Count:=1
    Selection.TypeText Text:="***"
    Selection.TypeParagraph
    Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    Options.DefaultHighlightColorIndex = wdRed
    Selection.Range.HighlightColorIndex = wdRed
    Selection.MoveRight Unit:=wdCharacter, Count:=1
End Sub

Upvotes: 1

Views: 6897

Answers (1)

RBarrett
RBarrett

Reputation: 11

Try putting the following construct within your With.Selection.Find

Do While .Execute
  '(logic that you want to apply after finding string)
Loop

In your case, your code would look like

Sub HighlightNewItems()
'
' HighlightNewItems Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "B,"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False

      Do While .Execute
        Selection.MoveUp Unit:=wdLine, Count:=2
        Selection.MoveLeft Unit:=wdWord, Count:=1
        Selection.TypeText Text:="***"
        Selection.TypeParagraph
        Selection.EndKey Unit:=wdLine, Extend:=wdExtend
        Options.DefaultHighlightColorIndex = wdRed
        Selection.Range.HighlightColorIndex = wdRed
        Selection.MoveRight Unit:=wdCharacter, Count:=1
      Loop 

    End With

End Sub

Upvotes: 1

Related Questions