Share via


Working with Text in a Range Object

You use a Range object's Text property to specify or determine the text the range contains. For example, the following code first displays the text within a Range object, then changes it and displays the new text, and finally restores the original text:

Public Sub ChangeTextSample()
   ' This procedure illustrates how to use the Range object's Text
   ' property to copy and paste text into a document while
   ' maintaining the original paragraphs.
   '
   ' When the rngText variable is instantiated, it includes all of
   ' the text in the first paragraph in the active document plus the
   ' paragraph mark at the end of the paragraph. Note how the new
   ' text in the strNewText variable includes a paragraph mark
   ' (vbCrLf) to replace the mark removed when the orginal text was
   ' replaced.
   Dim rngText               As Range
   Dim strOriginalText       As String
   Dim strNewText            As String
   
   strNewText = "Now is the time to harness the power of VBA in Word." _
      & "This text is replacing the original text in the first " _
      & "paragraph. This is all done using only the Text property " _
      & "of the Range object!" _
      & vbCrLf
      
   Set rngText = ActiveDocument.Paragraphs(1).Range
   With rngText
      MsgBox .Text, vbOKOnly, "This is the original text."
      strOriginalText = .Text
      .Text = strNewText
      MsgBox .Text, vbOKOnly, "This is the new text inserted in paragraph 1."
      .Text = strOriginalText
      MsgBox "The original text is restored."
   End With
End Sub

In this example, the Range object's Text property is used to specify the text that appears in the document.

See Also

Working with Microsoft Word Objects | The Range Object | Creating, Defining, and Redefining a Range, | Determining Where the Range Is Located | Inserting Text in a Range | Understanding Paragraph Marks