Search code examples
vbams-officecpu-word

I want to highlight a word if it is not followed by another specific word using VB


So I'm a total newbie when it comes to using VB. I am trying to highlight a word when it is not followed by another specific word within the next two words. I tried the following code but it seems to just the first word. Many thanks in advance.

    Sub fek()
'
' 
'
'
 Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "n."
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute

    If Selection.Find.Found = True Then
        With Selection.Range
        
        .MoveStart wdWord, 2
        
        End With
        
        With Selection.Find
        .Text = "fek"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
                    End With
                    
                    End If
                    
        If Selection.Find.Found = False Then
        Selection.Range.HighlightColorIndex = wdYellow
            End If
End Sub

Solution

  • The code below should do what you want. You need to bear in mind that what Word defines as a Word can be different to what a human would, e.g. an IP address is counted as 7 words!

    Sub fek()
       Dim findRange As Range
       Dim nextWords As Range
       
       Set findRange = ActiveDocument.Content
       With findRange.Find
          .ClearFormatting
          .Text = "n."
          .Forward = True
          .Wrap = wdFindStop
          .Format = False
          .MatchCase = True
          .MatchWholeWord = False
          .MatchWildcards = False
          .MatchSoundsLike = False
          .MatchAllWordForms = False
       
          Do While .Execute = True
             'findRange is now the range of the match so set nextWords to the 2 next words
             Set nextWords = findRange.Next(wdWord)
             nextWords.MoveEnd wdWord, 3
             'look for the specific text in the next two words
             If InStr(nextWords.Text, "fek") = 0 Then findRange.HighlightColorIndex = wdYellow
             'collapse and move findRange to the end of the match
             findRange.Collapse wdCollapseEnd
             findRange.Move wdWord, 4
          Loop
       End With
    End Sub