简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM