Working with the Selection Object
Word Developer Reference |
When you work on a document in Microsoft Office Word, you usually select text and then perform an action, such as formatting the text or typing text. In Microsoft Visual Basic, it is usually not necessary to select text before modifying the text. Instead, you create a Range object that refers to a specific portion of the document. For information about defining Range objects, see Working with Range objects. However, when you want your code to respond to or change a selection, you can do so by using the Selection object.
If text is not already selected, use the Select method to select the text that is associated with a specific object and create a Selection object. For example, the following instruction selects the first word in the active document.
|
For more information, see Selecting text in a document.
If text is already selected, use the Selection property to return a Selection object that represents the current selection in a document. There can be only one Selection object per document, and it always accesses the current selection. The following example changes the formatting of the paragraphs in the current selection.
|
This example inserts the word "Hello" after the current selection.
|
This example applies bold formatting to the selected text.
|
The macro recorder often creates a macro that uses the Selection object. The following example was created using the macro recorder. This macro selects the first two words in the active document and applies bold formatting to them.
|
The following example accomplishes the same task without selecting the text or using the Selection object.
|