簡體   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