R – Font of all headings in a Word Document

ms-wordvba

I am trying to retrieve the font name and size of all the headings from a word document. Any idea how to get it?

Best Answer

The basic structure will be something like below:

Public Sub ShowFontAndSize()
    Dim singleLine As Paragraph
    Dim lineText As String

    For Each singleLine In ActiveDocument.Paragraphs
     Debug.Print singleLine.Range.Font.Name
     Debug.Print singleLine.Range.Font.Size
    Next singleLine
End Sub

The catch will be that this won't sense if there are different fonts and sizes on the same line. If that's a possibility, you will need to add another loop with For Each singleCharacter In singleLine.Range.Characters inside of the paragraphs loop.

Edit: A trickier problem is what to do with this data once you've collected it. Building up an array seems like the natural fit, but VBA arrays are borderline useless, since basic methods like .append() require you to redim the whole array. See http://www.cpearson.com/excel/VBAArrays.htm for more info if you would like to go down that road.

Related Topic