Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count words in a Microsoft Word document by document style?

In analogy to this question, I would like to script a VBA script that counts words formatted with a certain document style, more precisely: a certain paragraph style.

Sub CountTypeface()
    Dim lngWord As Long
    Dim lngCountIt As Long
    Const Typeface As String = "Calibri"
    Const MyFormat As String = "My Paragraph Style"
    'Ignore any document "Words" that aren't real words (CR, LF etc)
    For lngWord = 1 To ActiveDocument.Words.Count
        If Len(Trim(ActiveDocument.Words(lngWord))) > 1 Then
            If ActiveDocument.Styles(lngWord) = MyFormat Then
                lngCountIt = lngCountIt + 1
            End If
        End If
    Next lngWord

    MsgBox "Number of " & Typeface & " words: " & lngCountIt
End Sub

But running this code results in the runtime error:
runtime error "5941".: the requested member of the collection does not exist

Why does this happen and how to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re using your word count iterator as the index for the style collection. You have more words than Styles has indices, and the If would only be true one time, since you aren’t checking the word’s style.

Replace:

If ActiveDocument.Styles(lngWord) = MyFormat Then

With:

If ActiveDocument.Words(lngWord).Style = MyFormat Then
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading