1
votes

Suppose the following text in an MS Word 2007/2010 document, I have "testA" highlighted with blue and "testB" highlighted with green color: "This is testA and testB.". I want to programmatically replace testA with its background color index 2, and replace testB with its background color index 11. Ref: WdColorIndex Enumeration

I've tried the following but it has two issues:

  1. It replaces testA with 0 (the color index of default background) and testB with 2 (that is a color index of testA)
  2. While loop does not end

I would like the replaced text to be: "This is 2 and 11". Instead, I am getting: "This is 0 and 2".

Any corrections using VBA or C# will be ok.

Sub ReplaceHighlightedTextColor()

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

End Sub
1

1 Answers

3
votes

Try this:

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