【问题标题】:Using MS Word VBA how to Find and Replace highlighted text with the value of the highlight color使用 MS Word VBA 如何使用突出显示颜色的值查找和替换突出显示的文本
【发布时间】:2015-07-29 11:21:48
【问题描述】:

假设 MS Word 2007/2010 文档中有以下文本,“testA”用蓝色突出显示,“testB”用绿色突出显示:“这是 testA 和 testB。”。我想以编程方式将 testA 替换为其背景颜色索引 2,并将 testB 替换为其背景颜色索引 11。参考:WdColorIndex Enumeration

我尝试了以下方法,但有两个问题:

  1. 它将 testA 替换为 0(默认背景的颜色索引),将 testB 替换为 2(即 testA 的颜色索引)
  2. 虽然循环没有结束

我希望替换的文本是:“这是 2 和 11”。相反,我得到:“这是 0 和 2”。

任何使用 VBA 或 C# 的更正都可以。

Sub ReplaceHighlightedTextColor()

    With Selection.Find
        .ClearFormatting
        .Highlight = True
        While .Execute(Forward:=True, Format:=True, ReplaceWith:=CStr(Selection.FormattedText.HighlightColorIndex))
        Wend
    End With

End Sub

【问题讨论】:

    标签: vba office-interop ms-word


    【解决方案1】:

    试试这个:

    Sub ReplaceHighlightedTextColor()
    
        Dim rng As Range
    
        Set rng = Selection.Range
    
        With rng.Find
    
            .ClearFormatting
            .Highlight = True
    
            While .Execute(Forward:=True, Format:=True) 
                'Note: 'rng' is now the range containing the matched content
                rng.Text = rng.FormattedText.HighlightColorIndex
            Wend
    
        End With
    
    End Sub
    

    【讨论】:

    • 优秀。谢谢您的帮助。特别是您在代码中的一行注释帮助我理解了这个问题。此外,您的代码让我明白(至少我认为)我的代码中的循环没有结束,因为我在 execute 方法中有 ReplaceWith 参数。
    • 这对我也很有教育意义:我不知道每次调用 Execute 时原始范围都会重新定义为“找到”范围。
    • @TimWilliams 你知道如何仅在突出显示颜色为绿色时才替换文本吗?
    猜你喜欢
    • 1970-01-01
    • 2012-01-26
    • 2018-10-03
    • 2011-07-12
    • 2019-07-04
    • 2023-01-31
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多