Looping through the parts of a non-contiguous selection in MS *Word* VBA

你说的曾经没有我的故事 提交于 2019-12-04 05:28:59

问题


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.



来源:https://stackoverflow.com/questions/36407694/looping-through-the-parts-of-a-non-contiguous-selection-in-ms-word-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!