Word VBA: Counting Words in Active Page

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

Macro Example

Sub GetWordsCount_ActivePage()

  MsgBox ActiveDocument.Bookmarks("\Page") _
    .Range.ComputeStatistics(wdStatisticWords)

End Sub

Description

[Application.]ActiveDocument

  ActiveDocument...

The Application.ActiveDocument property returns an active Document object.

obj-Word-Application-ActiveDocument

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

obj-Word-ActiveDocument

ActiveDocument.Bookmarks (Document.Bookmarks)

  ActiveDocument.Bookmarks...

The ActiveDocument.Bookmarks (Document.Bookmarks property) returns a Bookmarks collection object that represents all the bookmarks in the active document.

obj-Word-Document-Bookmarks

Bookmarks(“\Page”) (Bookmarks.Item)

  ActiveDocument.Bookmarks("\Page")...

The Bookmarks(“\Page”) (Bookmarks.Item method) returns an individual Bookmark object from the Bookmarks collection.

obj-Word-Bookmarks-Item

Because the Item method is a default member of the Bookmarks collection object, we can omit the .Item.

So, the Bookmarks(“\Page”) is equal Bookmarks.Item(“\Page”).

And the Bookmarks(“\Page”) returns the active page of the document by the predefined bookmark named “\Page”.

Bookmarks(“\Page”).Range (Bookmark.Range)

  ActiveDocument.Bookmarks("\Page") _
    .Range...

The Bookmarks(“\Page”).Range (Bookmark.Range property) returns the Range object that represents the portion of a document.

obj-Word-Document-Range

Range.ComputeStatistics

  ActiveDocument.Bookmarks("\Page") _
    .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.Bookmarks("\Page") _
    .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.Bookmarks(“\Page”).Range.ComputeStatistics(wdStatisticWords) is set to the parameter of a MsgBox function.

Sub GetWordsCount_ActivePage()

  MsgBox ActiveDocument.Bookmarks("\Page") _
    .Range.ComputeStatistics(wdStatisticWords)

End Sub

So, a message box shows the count of words on the active page.

Properties

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

Apply To

  • Word 2013
  • Word 2010
  • Word 2007