Word VBA: Getting the Index Number of the Current Paragraph

Sometimes we need to get the index number of the current paragraph in a document when we make a macro.

Macro Example

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

Sub GetIndexNumberOfCurrentParagraph()

  MsgBox ActiveDocument.Range(0, Selection.End).Paragraphs.Count

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.Range (Document.Range)

  ActiveDocument.Range...

The Document.Range method (ActiveDocument.Range) returns a Range object that represents a contiguous area in the document by using the specified starting (the 1st parameter) and ending (the 2nd parameter) character positions.

obj-Word-Document-Range

The following code refers to the range that starts at the beginning of the active document and ends at the cursor position.

  ActiveDocument.Range(0, Selection.End)...

Selection.End

The Selection.End property returns or sets the ending character position of a selection.

obj-Word-Selection-End

Range.Paragraphs

  ActiveDocument.Range(0, Selection.End).Paragraphs...

The Range.Paragraphs property returns a Paragraphs collection object that represents all the paragraphs in the range.

obj-Word-Range-Paragraphs

Paragraphs.Count

  ActiveDocument.Range(0, Selection.End).Paragraphs.Count

The Paragraphs.Count property returns a Long integer value that represents the count of paragraphs.

obj-Word-Paragraphs-Count

MsgBox function

The code: ActiveDocument.Range(0, Selection.End).Paragraphs.Count is set to the parameter of a MsgBox function.

Sub GetIndexNumberOfCurrentParagraph()

  MsgBox ActiveDocument.Range(0, Selection.End).Paragraphs.Count

End Sub

So, a message box shows the index number of the current paragraph in an active document.

Properties

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

Apply To

  • Word 2013
  • Word 2010
  • Word 2007