Word

Get Line and Paragraph Number

Ease of Use

Intermediate

Version tested with

97 

Submitted by:

Steiner

Description:

This is a collection of three small functions that provide the line number on the current page, the abolute line number in the document, and the paragraph number in the document. 

Discussion:

Sometimes you need to refer to the line number of a certain bookmark or other object. Here, we provide three methods of functionality that MS should have included, but has not. Our sample file provides messageboxes to report the location. Likely, you will not use this method, but will use this code with other code to perform your task(s). 

Code:

instructions for use

			

Sub WhereAmI() MsgBox "Paragraph number: " & GetParNum(Selection.Range) & vbCrLf & _ "Absolute line number: " & GetAbsoluteLineNum(Selection.Range) & vbCrLf & _ "Relative line number: " & GetLineNum(Selection.Range) End Sub Function GetParNum(r As Range) As Integer Dim rParagraphs As Range Dim CurPos As Long r.Select CurPos = ActiveDocument.Bookmarks("\startOfSel").Start Set rParagraphs = ActiveDocument.Range(Start:=0, End:=CurPos) GetParNum = rParagraphs.Paragraphs.Count End Function Function GetLineNum(r As Range) As Integer 'relative to current page GetLineNum = r.Information(wdFirstCharacterLineNumber) End Function Function GetAbsoluteLineNum(r As Range) As Integer Dim i1 As Integer, i2 As Integer, Count As Integer, rTemp As Range r.Select Do i1 = Selection.Information(wdFirstCharacterLineNumber) Selection.GoTo what:=wdGoToLine, which:=wdGoToPrevious, Count:=1, Name:="" Count = Count + 1 i2 = Selection.Information(wdFirstCharacterLineNumber) Loop Until i1 = i2 r.Select GetAbsoluteLineNum = Count End Function

How to use:

  1. Copy the code above.
  2. Open your document.
  3. Hit Alt +F11 to open the Visual Basic Editor (VBE).
  4. Double-click your document's name at left.
  5. Choose Insert-Module from the menu.
  6. Paste the code you copied.
  7. Close the VBE.
 

Test the code:

  1. Place your cursor somewhere inside the document.
  2. Hit Tools-Macro-Macros and double-click WhereAmI to display a dialog pointing out your current position.
 

Sample File:

Position.zip 7.78KB 

Approved by mdmackillop


This entry has been viewed 263 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express