Reputation: 387
I have a word count function that looks for text that is either Highlighted or Bold and Un-Underlined and then returns the number of words in a document that meet that criteria.
However the results differ from the results returned by the Find function in word by a significant margin, anyone have any idea why the discrepancy might be occurring? Am I double-counting something?
Sub CountWords()
Dim rngWords As Range
Set rngWords = ActiveDocument.Content
Dim boldCount As Long, highlightCount As Long
Dim wordTotal As Long
Do
With rngWords.Find
.Highlight = True
.Forward = True
.Execute
End With
If rngWords.Find.Found = True Then
highlightCount = highlightCount + rngWords.Words.Count
Else
Exit Do
End If
Loop
Set rngWords = ActiveDocument.Content
Do
With rngWords.Find
.Font.Bold = True
.Highlight = False
.Font.Underline = wdUnderlineNone
.Forward = True
.Execute
End With
If rngWords.Find.Found = True Then
boldCount = boldCount + rngWords.Words.Count
Else
Exit Do
End If
Loop
wordTotal = boldCount + highlightCount
MsgBox "There are " & wordTotal & " words to be spread"
End Sub
Upvotes: 2
Views: 1555
Reputation: 33175
The Words property counts punctuation and paragraph marks. Change
highlightCount = highlightCount + rngWords.Words.Count
to
highlightCount = highlightCount + rngWords.ComputeStatistics(wdStatisticWords)
and they will match.
Upvotes: 4