【问题标题】:Word VBA Alternate Word Highlighting using VBA使用 VBA 的 Word VBA 替代单词突出显示
【发布时间】:2011-07-12 16:57:42
【问题描述】:

您好,场景如下:我需要以红色和绿色的交替颜色突出显示单词,并且我的以下代码已经在工作。问题是,如何在不使用 Mod 或 Modulo 运算符的情况下做到这一点?它也应该使用范围。欢迎任何建议!多谢你们!

调用函数的模块:

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

【问题讨论】:

  • 你为什么要消除Mod?这是作业吗?

标签: vba ms-word range highlight


【解决方案1】:

在计算机能够快速进行除法之前,有两种常见的交替事物的方法。

整数的最低有效位在递增时将在 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

【讨论】:

  • 嗨,加布。感谢您的快速回复。我更喜欢你的代码而不是我的代码,哈哈!感谢您消除了我对替代品的一些困惑。这很快就会派上用场。 :)
  • 哦,最后一个问题:有没有比上面使用 For Each eachWord In R.Words 更好的方法来做替代颜色?
猜你喜欢
  • 2012-01-26
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多