Determining the largest/smallest font size in a selection?

A

Andreas Baus

Selection.Font.Size returns wdUndefined when the Selection contains
portions of text with different font sizes (of course, this makes
sense since the range then does not have one definite font size). Does
anyone know if there is an way to determine at least for example the
largest or smallest font size used in the selected range efficiently
(i.e. a solution that does *not* involve iterating over and checking
every single character, if possible...)?
All suggestions will be highly appreciated.
 
K

Klaus Linke

Hi Andreas,

Recursively halving the range until you don't get wdUndefined should be
pretty fast... See macros below.
Hope I got the logic right... you should run a few tests.

Regards,
Klaus


Sub SelectionFontSize()
' select some text and run this macro
Dim rng As Range
Dim min As Single
Dim max As Single
' smallest possible size:
max = 1
' largest possible size:
min = 1638
Set rng = Selection.Range.Duplicate
Call MinMaxFontSize(rng, min, max)
MsgBox min & "/" & max, , "min/max font size"
End Sub

Sub MinMaxFontSize(rng As Range, min As Single, max As Single)
Dim myFontSize As Single
Dim rng1 As Range
Dim rng2 As Range
myFontSize = rng.Font.Size
If rng.Font.Size = wdUndefined Then
Set rng1 = rng.Duplicate
Set rng2 = rng.Duplicate
rng1.End = rng.Start + Int(0.5 * (rng.End - rng.Start))
rng2.Start = rng1.End + 1
Call MinMaxFontSize(rng1, min, max)
Call MinMaxFontSize(rng2, min, max)
Else
If myFontSize < min Then
min = myFontSize
Else
If myFontSize > max Then
max = myFontSize
End If
End If
End If
End Sub
 
K

Klaus Linke

I knew I'd blow this!
Change

If myFontSize < min Then
min = myFontSize
Else
If myFontSize > max Then
max = myFontSize
End If
End If

to

If myFontSize < min Then
min = myFontSize
End If
If myFontSize > max Then
max = myFontSize
End If


BTW, another thing you could try is to collapse the selection to the start,
then use
Selection.SelectCurrentFont

You now can be sure that you don't get wdUndefined for the font size.
Collapse to the end, rinse and repeat, until you are at the end of the
range.

Or get the size of the first character, and use "Edit > Find" for this font
size. Then collapse to the end, rinse and repeat.

The last method should also be pretty fast.
"Find" matches one paragraph at a time whereas the recursive macro can get
the size for several paragraphs in one go.
OTOH, the recursive macro may get wdUndefined quite often, before it
determines the real font size.

Regards,
Klaus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top