简体   繁体   中英

VBA Count words in a Microsoft Word document by Color

Would it be possible to count color word inside a Word documents. Let say there are two color word in my document. I need to count word which the color is Blue and I need to count word which the color is Red.

I only found "Count words in a Microsoft Word document by Fonts"

using below script:

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

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

Please advice.

Thank you.

Try with this:

Option Explicit

Sub CountTypeface()
    Dim lngWord As Long
    Dim lngCountIt As Long
    Const ColorIndex As Long = 6

    For lngWord = 1 To ActiveDocument.Words.Count
        If Len(Trim(ActiveDocument.Words(lngWord))) > 1 Then
            Debug.Print ActiveDocument.Words(lngWord).Font.ColorIndex
            If ActiveDocument.Words(lngWord).Font.ColorIndex = ColorIndex Then
                lngCountIt = lngCountIt + 1
            End If
        End If
    Next lngWord

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

6 is for red. If you put a small text in Word and you color a few words, it would print them their colors in the immediate window, before giving you the messagebox. Thus, you would learn the number of the colors.

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