Search code examples
vbams-wordhighlight

Running highlight macro in specific styles


Below code is trying to highlight words in MS word file that were in lowercase. However I only need it to run in 3 specific Styles (Heading Level 1, Heading Level 2 and Heading Level 3) . Any help on how to also run this to other two specific styles? Thank you in advance.

Option Explicit

Dim myDoc As Document: Set myDoc = ActiveDocument

Dim myPara As Word.Paragraph
For Each myPara In myDoc.StoryRanges.Item(wdMainTextStory).Paragraphs

    If myPara.Style.NameLocal = "Heading Level 1" Then

        TitleParagraph myPara

   End If

Next

End Sub

Public Sub TitleParagraph(ByVal ipPara As Word.Paragraph)

Dim myText As Range
For Each myText In ipPara.Range.Words

    If LCase$(myText.Text) = myText.Text Then

        myText.Words.Item(1).HighlightColorIndex = wdTurquoise

    End If

Next
End Sub

Solution

  • The following is a way more efficient approach to the problem:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim i As Long, h As Long
    h = Options.DefaultHighlightColorIndex
    Options.DefaultHighlightColorIndex = wdTurquoise
    With ActiveDocument.Range.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Format = True
      .Forward = True
      .MatchWildcards = True
      .Text = "<[a-z]@>"
      .Replacement.Text = "^&"
      .Replacement.Highlight = True
      .Wrap = wdFindContinue
      For i = 1 To 3
        .Style = "Heading " & i
        .Execute Replace:=wdReplaceAll
      Next
    End With
    Options.DefaultHighlightColorIndex = h
    Application.ScreenUpdating = True
    End Sub