繁体   English   中英

使用MS Word VBA如何使用突出显示颜色的值查找和替换突出显示的文本

[英]Using MS Word VBA how to Find and Replace highlighted text with the value of the highlight color

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

我尝试了以下但它有两个问题:

  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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM