Search code examples
vbams-wordrangehighlight

Word VBA Alternate Word Highlighting using VBA


Hi heres the scenario: I need to highlight words in alternating colors of red and green and i have the following code that is already working. Question is, how can this be done without using the Mod or Modulo operator? It should also be using Range. Any suggestions are welcomed! Thanks guys!

Module to call the Function:

Sub Test()
'If to call the function
If (altHighlight(ActiveDocument.Range)) = True Then MsgBox "Alternate Highlighting Done!"

End Sub

Function for alternate highlighting:

Function altHighlight(R As Range) As Boolean
    Dim eachWord As Range
    Dim count As Integer

    For Each eachWord In R.Words
        If count Mod 2 = 0 Then
            eachWord.HighlightColorIndex = wdRed
        Else
            eachWord.HighlightColorIndex = wdGreen
        End If
        count = count + 1
    Next
    altHighlight = True
End Function

Solution

  • Before computers could do division quickly, there were two common ways to alternate things.

    The least significant bit of an integer will alternate between 0 and 1 as it is incremented. You can use the bitwise AND operator to single out that bit:

    Function altHighlight(R As Range) As Boolean
        Dim eachWord As Range
        Dim count As Integer
    
        For Each eachWord In R.Words
            If count And 1 = 0 Then
                eachWord.HighlightColorIndex = wdRed
            Else
                eachWord.HighlightColorIndex = wdGreen
            End If
            count = count + 1
        Next
        altHighlight = True
    End Function
    

    Since you're not actually counting the items in your range, you can just make count itself toggle between 0 and 1:

    Function altHighlight(R As Range) As Boolean
        Dim eachWord As Range
        Dim count As Integer
    
        For Each eachWord In R.Words
            If count = 0 Then
                eachWord.HighlightColorIndex = wdRed
            Else
                eachWord.HighlightColorIndex = wdGreen
            End If
            count = 1 - count
        Next
        altHighlight = True
    End Function