Search code examples
vbams-wordwildcard

Find acronyms unless followed by open bracket character (


I have a macro that uses wildcards to find acronyms in a Word document.

I want to 'unhighlight' that acronym if it is followed by a (.
For example, my content might say "BRB (be right back)" so BRB would not be highlighted. But, LOL would be highlighted if (laughing out loud) does not immediately follow the text.

I am trying to avoid false positives. Is there way I can exclude the 'BRB' results?

With ActiveDocument.Content.Find
  .ClearFormatting
  .Text = "<[A-Z]{2,}>"
With .Replacement
  .Text = "^&"
  .ClearFormatting
  .Highlight = True
End With

Solution

  • Try this out:

    Sub HighlightAcronyms()
    
        Dim rng As Range, r2 As Range
    
        Set rng = ActiveDocument.Content
        Set r2 = ActiveDocument.Content
    
        With rng.Find
            .ClearFormatting
            .Text = "<[A-Z]{2,}>"
            .Forward = True
            .Wrap = wdFindStop
            .MatchCase = True
            .MatchWildcards = True
            .Format = False
    
            Do While .Execute
                'look two characters past the found acroynm
                r2.Start = rng.End + 1
                r2.End = rng.End + 3
                Debug.Print rng.Text, r2.Text
    
                'highlight if r2 has a "(" otherwise clear highlight
                rng.HighlightColorIndex = IIf(r2.Text Like "*(*", _
                                            wdAuto, wdYellow)
    
    
            Loop
        End With
    
    End Sub