Using VBA to learn details about the current selection in a Word document

Use this unique property to learn about the current selection in a Word document.

When manipulating Word data programmatically, you usually need to know a bit about the currently selected data. For instance, you might need to know what page the data resides on, what column the data is in, or how many pages are in the current document. Gleaning such specific information only sounds intimidating. The truth is, it's a simple task for Visual Basic for Applications (VBA). The solution is to reference the Selection object's Information property in the form Selection.Information(information) where information represents a number of defined parameters that return specific information about the current selection. Now, there are a number of these parameters. To see a complete list, search on Information Property in the Word Visual Basic Editor's (VBE) Help. Or, in the VBE, press F2 to launch the Object Browser. Enter Information in the Search Text control and click Search. Doing so will return several possibilities; Click the wdInformation class entry to see a complete list of this property's parameters. There are any number of ways to use this property, but we'll keep things simple by displaying the results of a few statements in the Immediate window. In Word's VBE, choose Module from the Insert menu and enter the following code: Sub SelectionInformation()   'Print information about selection.   Debug.Print "Column: " & _   Selection.Information(wdFirstCharacterColumnNumber)   Debug.Print "Line: " & _   Selection.Information(wdFirstCharacterLineNumber)   Debug.Print "Current Page: " & _   Selection.Information(wdActiveEndPageNumber)   Debug.Print "Total Pages: " & _   Selection.Information(wdNumberOfPagesInDocument) End Sub   Before running the code, make sure there's a document open. Then, return to the VBE and press [Ctrl]+G to open the Immediate window (if necessary). To run the code, click anywhere inside the actual sub procedure and press F5. Each Debug.Print statement concatenates a description, such as Column, Line, and so on to the results of the corresponding property and prints the results to the Immediate window.   This particular sub procedure isn't meant to actually do something that you can immediately employ in your own documents. Rather, it's an introduction to the Information property. Now that you know how to pass the appropriate parameter, you can learn just about anything you need to know about the current selection in a Word document.

About Susan Harkins

Susan Sales Harkins is an IT consultant, specializing in desktop solutions. Previously, she was editor in chief for The Cobb Group, the world's largest publisher of technical journals.

Editor's Picks