MS Word 宏:如何将选定文本内的突出显示从特定颜色更改为另一种颜色?

MS Word 宏:如何将选定文本内的突出显示从特定颜色更改为另一种颜色?

我想将所选文本(不是整个文档)中的黄色突出显示更改为红色突出显示。此 VBA 确实会更改突出显示的颜色,但它不会停留在所选文本上(它还会更改所选文本下方的突出显示)。

Sub SwitchHighlightsColor()
    Dim r As Range
    Set r = ActiveDocument.Range

    With r.Find
        .Highlight = True
        .Forward = True
        Do While .Execute(FindText:="", Forward:=True) = True
            If r.HighlightColorIndex = wdYellow Then   ' Highlight color you want to change
                r.HighlightColorIndex = wdRed          ' the new Highlight color you want to have
                r.Collapse 0
            End If
        Loop
    End With
End Sub

答案1

尝试进行以下修改:

Sub SwitchHighlightsColor()
    Dim r As Range
    Set r = Application.Selection.Range

    With r.Find
        .Highlight = True

        Do While .Execute(FindText:="") And r.InRange(Application.Selection.Range)
            If r.HighlightColorIndex = wdYellow Then   ' Highlight color you want to change
                r.HighlightColorIndex = wdRed          ' the new Highlight color you want to have
                r.Collapse 0
            End If
        Loop
    End With
End Sub

在此处输入图片描述

在此处输入图片描述

在此处输入图片描述

编辑:

此替代代码以字母为基础,而不是以单词为基础。因此,它应该会将所有突出显示的字母更改为正确的颜色。但是,这将很难撤消,因为您需要逐个撤消每个字母,而不是一次性撤消所有字母。

Sub SwitchHighlightsColorPerLetter()
    Dim r As Range
    Set r = Application.Selection.Range

    With r.Find
        .Highlight = True

        Do While .Execute(FindText:="") And r.InRange(Application.Selection.Range)
            For Each x In r.Characters
                If x.HighlightColorIndex = wdYellow Then   ' Highlight color you want to change
                    x.HighlightColorIndex = wdRed          ' the new Highlight color you want to have
                    x.Collapse 0
                End If
            Next
        Loop
    End With
End Sub

相关内容