Word VBA: Counting Words in Selection

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

Macro Example

Sub GetWordsCount_Selection()

  MsgBox Selection.Range.ComputeStatistics(wdStatisticWords)

End Sub

Description

[Application.]Selection

  Selection...

The Application.Selection property returns the Selection object that represents a selected range or the insertion point.

obj-Word-Application-Selection

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

obj-Word-Global-Selection

Selection.Range

  Selection.Range...

The Selection.Range property returns the Range object that represents the portion of a document.

obj-Word-Document-Range

Range.ComputeStatistics

  Selection.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

  Selection.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: Selection.Range.ComputeStatistics(wdStatisticWords) is set to the parameter of a MsgBox function.

Sub GetWordsCount_Selection()

  MsgBox Selection.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