Word VBA: Counting Sections in a Document

Sometimes, I must count sections in a document when I make a Word macro.

Macro Example

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

Sub GetSectionsCount()

  MsgBox ActiveDocument.Sections.Count

End Sub

Description

ActiveDocument property

  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

Document.Sections property

  ActiveDocument.Sections...

The Document.Sections property (ActiveDocument.Sections) returns the Sections collection object that represents sections in a document.

obj-Word-Document-Sections

Sections.Count property

  ActiveDocument.Sections.Count

The Sections.Count property returns a long integer value that represents the number of sections in a document.

obj-Word-Sections-Count

The code: ActiveDocument.Sections.Count is set to the parameter of a MsgBox function.

Sub GetSectionsCount()

  MsgBox ActiveDocument.Sections.Count

End Sub

So, the sections count will be displayed in a message box.

Properties

http://www.relief.jp/itnote/archives/018304.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007