Word VBA: Getting the Total Number of Pages in a Document

Sometimes we need to get the total number of pages in a Word document when we make a macro.

Macro Example

The following Word VBA macro displays it in a message box.

Sub GetNumberOfPagesInDocument()

  MsgBox ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

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

ActiveDocument.Range (Document.Range)

  ActiveDocument.Range...

The ActiveDocument.Range (Document.Range method) returns a Range object that represents a contiguous area in the document.

obj-Word-Document-Range

Range.Information

  ActiveDocument.Range.Information...

The Range.Information property returns information about the range.

obj-Word-Range-Information

Const: wdNumberOfPagesInDocument

  ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

We can get the number of pages in a document by setting the const: wdNumberOfPagesInDocument to the parameter of the Range.Information property.

obj-Word-WdInformation-wdNumberOfPagesInDocument

MsgBox function

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

Sub GetNumberOfPagesInDocument()

  MsgBox ActiveDocument.Range.Information(wdNumberOfPagesInDocument)

End Sub

So, a message box shows the total pages number of the active document.

Properties

http://www.relief.jp/itnote/archives/word-vba-get-page-number.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007