Word Macros, Recovered

The upgrade to Office 2013 killed my word macros which were in normal.dot or some kind of global template. I did some work today to recover them using old copies, which I had backed up to Evernote and here on my blog.

I spent a bit of time trying to get them to work better. The search with formatting can be a bit surprising. I think I came up with a good way to search through the contents of a file from start to finish by getting the page number of a selection and ending the loop when we get to a point where the page number of the current selection is lower than the page number of the previous selection. (see ABB_highlight_brute)

Here they are. Copy and paste if they help you. And, feel free to drop me a note if you do on twitter: @francisluong

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