This topic includes Visual Basic examples related to the following tasks:
For information about and examples of other editing tasks, see the following topics:
Returning text from a document
Manipulating a portion of a document
Determining whether text is selected
The Type property of the Selection object returns information about the type of selection. The following example displays a message if the selection is an insertion point.
If Selection.Type = wdSelectionIP Then MsgBox "Nothing is selected"
Collapsing a selection or range
Use the Collapse method to collapse a Selection or Range object to it's beginning or ending point. The following example collapses the selection to an insertion point at the beginning of the selection.
Selection.Collapse Direction:=wdCollapseStart
The following example cancels the myRange
object to it's ending point (after the first word).
Set myRange = ActiveDocument.Words(1)
myRange.Collapse Direction:=wdCollapseEnd
Extending a selection or range
The following example uses the MoveEnd method to extend the end of the selection to include three additional words. The MoveLeft, MoveRight, MoveUp and MoveDown methods can also be used to extend a Selection object.
Selection.MoveEnd Unit:=wdWord, Count:=3
The following example uses the MoveEnd method to extend oRange
to include the first three paragraphs in the active document.
Set oRange = ActiveDocument.Paragraphs(1).Range
oRange.MoveEnd Unit:=wdParagraph, Count:=2
Redefining a Range object
Use the SetRange method to redefine an existing Range object. For more information, see Working with Range objects.
Changing text
You can change existing text by changing the contents of a range. The following instruction changes the first word in the active document by setting the Text property to "The."
ActiveDocument.Words(1).Text = "The "
You can also use the Delete method to delete existing text and then insert new text using the InsertAfter or InsertBefore method. The following example deletes the first paragraph in the active document and inserts new text.
Set myRange = ActiveDocument.Paragraphs(1).Range
With myRange
.Delete
.InsertAfter Text:="New text"
.InsertParagraphAfter
End With