Looping through the parts of a non-contiguous sele

2019-03-02 06:49发布

问题:

I have a macro in MS Word 2013 VBA (not Excel) that toggles the selected text's highlight color. Code looks like this:

If Selection.Range.HighlightColorIndex = WhtColor Then Selection.Range.HighlightColorIndex = wdNoHighlight Else Selection.Range.HighlightColorIndex = WhtColor

That works great for continuous/contiguous selections. But, if I select, say, 4 non-contiguous rows in a Word table (say, rows 5, 12, 15, and 19), the macro highlights only the last row selected.

How do I get the HighlightColorIndex to apply to all "parts" of the noncontiguous range, or, how do I loop through the different "parts" of the range and apply the HighlightColorIndex to each part?

回答1:

The web page that Tim Williams points to (support.microsoft.com/en-us/kb/288424) gives a clue about how this is possible. But, that link does show that one cannot loop through a non-contiguous selection.

Nevertheless, what that link also shows is that Font formatting can be set for a non-contiguous selection, but not for a range object.

Here is the revised code that does work for a non-contiguous selection:

If Selection.Font.Shading.BackgroundPatternColor = WhtColor Then Selection.Font.Shading.BackgroundPatternColor = wdColorAutomatic Else Selection.Font.Shading.BackgroundPatternColor = WhtColor

That code will change the background color to the target color selected (although I had to change the color codes from Wd constants to WdColor constants).

The only drawback with this approach is that I do not know a way to search for text whose background color has been changed, whereas you can search for text that is highlighted.

Anyway, thanks, @Tim Williams for the helpful link. Hope the above helps someone else who just wants to change font properties and does not actually have to loop through the separate pieces of the selected range.