使用VBA的Word VBA替代词突出显示

时间:2011-03-10 12:56:53

标签: range highlighting word-vba

嗨继承人的情景:我需要突出红色和绿色的交替颜色的单词,我有以下代码已经工作。问题是,如何在不使用Mod或Modulo运算符的情况下完成此操作?它也应该使用Range。欢迎任何建议!多谢你们!

调用函数的模块:

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

End Sub

备用突出显示的功能:

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

1 个答案:

答案 0 :(得分:0)

在计算机快速完成分工之前,有两种常用的方法来交替。

整数的最低有效位在递增时将在0和1之间交替变换。您可以使用按位AND运算符来单独输出该位:

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

由于您实际上并未计算范围内的项目,因此您只需将count自身在0和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