Word VBA Macros – Count Words in Selection
Count Words in Selection
This Word VBA Macro will count the number of words in the selection. If no selection is made, it will count the number of words in the entire document.
Sub WordCount()
'counts whole doc, then word Count for selection (if something is selected)
Dim nWordsCount As Long
Dim nCharCount As Long
nWordsCount = ActiveDocument.Range.ComputeStatistics(wdStatisticWords)
nCharCount = ActiveDocument.Range.ComputeStatistics(wdStatisticCharacters)
MsgBox "The entire doc contains: " & vbCrLf & nWordsCount & " words and" & vbCrLf & _
nCharCount & " characters without spaces", , "Word Count"
'now show word count for selected text
If Selection.Words.Count >= 1 And Selection.Type <> wdSelectionIP Then
nWordsCount = Selection.Range.ComputeStatistics(wdStatisticWords)
nCharCount = Selection.Range.ComputeStatistics(wdStatisticCharacters)
MsgBox "Selected text contains: " & vbCrLf & nWordsCount & " words and" & vbCrLf & _
nCharCount & " characters without spaces", , "Word Count (selection)"
End If
End Sub