Word VBA: Counting Words in Active Document

Sometimes, I want to count the number of words in a document when I make a Word macro.

Macro Example

The following Word VBA macro shows a message box with the number of words in an active document.

Sub GetWordsCount()

  MsgBox ActiveDocument.Range.ComputeStatistics(wdStatisticWords)

End Sub

Description

[Application.]ActiveDocument

  ActiveDocument...

The Application.ActiveDocument property returns an active Document object.

obj-Word-Application-ActiveDocument

The ActiveDocument property is a member of the Word.Global class, so we can omit the Application property.

obj-Word-ActiveDocument

ActiveDocumet.Range [Document.Range]

  ActiveDocument.Range...

The ActiveDocument.Range (Document.Range method) returns a specified Range object on an active document.

obj-Word-Document-Range

Range.ComputeStatistics

  ActiveDocument.Range.ComputeStatistics...

The Range.ComputeStatistics method returns a Long integer value represents a statistic based on the contents of the specified range.

obj-Word-Range-ComputeStatistics

Getting the Count of Words

  ActiveDocument.Range.ComputeStatistics(wdStatisticWords)

We can get the count of words by setting the const: wdStatisticWords to the argument of the Range.ComputeStatistics method.

MsgBox function

The code: ActiveDocument.Range.ComputeStatistics(wdStatisticWords) is set to the parameter of a MsgBox function.

Sub GetWordsCount()

  MsgBox ActiveDocument.Range.ComputeStatistics(wdStatisticWords)

End Sub

So, a message box shows the count of words.

Properties

http://www.relief.jp/itnote/archives/word-vba-count-number-of-words.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007