简体   繁体   中英

Count words in a Microsoft Word document by font?

I have a large document with code samples in. I want to know the word count for all text in font Calibri (Body), regardless of size. I want to ignore Consolas etc.

I have a macro that counts by italic (posted as an example) but can't get it to run.

Sub IgnoreItalics()
    Dim lngWord As Long, lngCountIt As Long

    lngCountIt = 0

    For lngWord = 1 To ActiveDocument.Words.Count
        If ActiveDocument.Words(lngWord).Italic Then
            lngCountIt = lngCountIt + 1
        End If
    Next lngWord

    MsgBox "Number of non-italic words: " & _
    ActiveDocument.BuiltInDocumentProperties("Number of words") -
    lngCountIt
End Sub

Any idea how to change this to Consolas?

Modifying your code so you can hopefully understand it, here is a solution that works for me

Sub CountTypeface()
    Dim lngWord As Long
    Dim lngCountIt As Long
    Const Typeface As String = "Calibri"

    For lngWord = 1 To ActiveDocument.Words.Count
        'Ignore any document "Words" that aren't real words (CR, LF etc)
        If Len(Trim(ActiveDocument.Words(lngWord))) > 1 Then
            If ActiveDocument.Words(lngWord).Font.Name = Typeface Then
                lngCountIt = lngCountIt + 1
            End If
        End If
    Next lngWord

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

For the record, changing your code just a tad worked for me:

Sub CountFonts()

Dim lngWord As Long, lngCountIt As Long
lngCountIt = 0
For lngWord = 1 To ActiveDocument.Words.Count
If ActiveDocument.Words(lngWord).Font.Name = "Calibri" Then
lngCountIt = lngCountIt + 1
End If
Next lngWord

MsgBox "Number of non-Calibri words: " & _
ActiveDocument.BuiltInDocumentProperties("Number of words") - lngCountIt
End Sub

use

ActiveDocument.ComputeStatistics(wdStatisticWords)

or

ActiveDocument.ComputeStatistics(0)

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