Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Working with the Selection Object

Office 2007

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.

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

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.

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

This example inserts the word "Hello" after the current selection.

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

This example applies bold formatting to the selected text.

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

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.

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 selecting the text or using the Selection object.

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


Community Additions

Show:
© 2014 Microsoft