Working with the Selection Object

Microsoft Word Visual Basic

Working with the Selection Object

   

When you work on a document in Word, you usually select text and then perform an action, such as formatting the text or typing text. In 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 on defining Range objects, see Working with Range objects. However, when you want your code to respond to or change the selection, you can do so with the Selection object.

The Select method activates an object. For example, the following instruction selects the first word in the active document.

Sub SelectFirstWord()
    ActiveDocument.Words(1).Select
End Sub

For more information, see Selecting text in a document.

The Selection property returns a Selection object that represents the active selection in a document window pane. There can only be one Selection object per document window pane and only one Selection object can be active. For example, the following example changes the paragraph formatting of the paragraphs in the selection.

Sub FormatSelection()
    Selection.Paragraphs.LeftIndent = InchesToPoints(0.5)
End Sub

For example, the following example inserts the word "Hello" after the selection.

Sub InsertTextAfterSelection()
    Selection.InsertAfter Text:="Hello "
End Sub

The following example applies bold formatting to the selected text.

Sub BoldSelectedText()
    Selection.Font.Bold = True
End Sub

The macro recorder will often create a macro that uses the Selection property. The following example was created using the macro recorder. The macro applies bold formatting to the first two words in the document.

Sub Macro()
    Selection.HomeKey Unit:=wdStory
    Selection.MoveRight Unit:=wdWord, Count:=2, Extend:=wdExtend
    Selection.Font.Bold = wdToggle
End Sub

The following example accomplishes the same task without using the Selection property.

Sub WorkingWithRanges()
    ActiveDocument.Range(Start:=0, _
        End:=ActiveDocument.Words(2).End).Bold = True
End Sub