Francis Luong

View Original

Word VBA Macro: Loop and Highlight Lines Matching Search Text

I’m starting to get more sophisticated vs. my previous attempt, which involved more duplication of code. This code is easier to debug than the version in my previous post because it doesn’t needlessly repeat any stretches of code.

Sub highlight_test_results()
'
' highlight_test_results Macro
' Find instances of "Test Result:" which are not highlighted and:
'  - extend selection to end of line`
'  - highlight it
'

Dim iCount As Integer
Dim searchDone As Boolean
Dim searchTextArray(0 To 0) As String
Dim searchText As Variant
searchTextArray(0) = "Test Result:"
Options.DefaultHighlightColorIndex = wdYellow

For Each searchText In searchTextArray

    Selection.HomeKey Unit:=wdStory

    searchDone = False
    iCount = 0

    Do While searchDone = False And iCount < 1000

        iCount = iCount + 1

        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Forward = True
            .Wrap = wdFindContinue
            .Text = searchText
            .Highlight = False
        End With
        Selection.Find.Execute

        If Selection.Find.Found Then
            Selection.EndOf Unit:=wdLine, Extend:=wdExtend
            Selection.Range.HighlightColorIndex = wdYellow

        Else: searchDone = True
        End If
    Loop
Next searchText

End Sub