Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Word VBA - Determine extent of "style run"?

Tags:

Suppose I have a Range reference in Word VBA, and I want to break that down into smaller ranges where the formatting (font, colour, etc.) is identical. For example, if I start with:

The quick brown fox jumped over the lazy dog.

...then I would want to get back 5 ranges, as follows:

The

quick

brown fox jumped over the

lazy

dog.

I had hoped that there was a built-in way to do this in VBA (and even have a phantom memory of using such a facility), but I can't find anything.

I could do what I need to do in code, but something that works natively would be much (much) quicker.

[In code, I would use the fact that - for example - oRange.Font.Bold will return "undefined" if the range contains a mix of bold and not bold, and so I could use this repeatedly to discover the extent of the uniform ranges. But I'm pretty sure that Word will be doing this under the hood, so if someone can pop that hood for me, I'd be grateful.]

EDIT: removed more complex example that the StackOverflow HTML renderer did not like.

like image 837
Gary McGill Avatar asked Nov 24 '09 15:11

Gary McGill


1 Answers

Can't really do this in VBA as the OM doesn't support runs (OOXML does however). The best you could probably do is get the wdUnits of wdCharacterFormatting and create a loop to create ranges, extract their properties and then destroy them until the loop is finished. You'd probaby start with something like:

Dim sel As Selection
Set sel = ActiveWindow.Selection
Dim selRange As Range
Set selRange = selRange.Next(wdCharacterFormatting)

to get the start and end of the next set of formatting, like selRange.Start/selRange.End, as well as any properties like selRange.Font.Name/selRange.Bold.

like image 193
Todd Main Avatar answered Oct 11 '22 10:10

Todd Main