Inserting Text in a Range
You use the Range object's InsertBefore or InsertAfter methods to add text to an existing Range object. In fact, there is an entire class of methods, with names that begin with "Insert," that you can use to manipulate a Range object.
It's useful to have a procedure that combines the Range object's InsertBefore and InsertAfter methods with the Text property. Having such a procedure creates a single place to handle much of the work you will do when manipulating text programmatically.
You can call the InsertTextInRange procedure when you must add text to a Range object. In other words, the procedure is useful when you want to programmatically make any changes to existing text in a Word document.
The InsertTextInRange procedure uses one required arguments and two optional argument. The strNewText argument contains the text you want to add to the Range object specified in the rngRange argument. The intInsertMode optional argument specifies how the new text will be added to the range. The values for this argument are one of three custom enumerated constants that specify whether to use the InsertBefore method, the InsertAfter method, or the Text property to replace the existing range text.
Public Function InsertTextInRange(strNewText As String, _
Optional rngRange As Word.Range, _
Optional intInsertMode As opgTextInsertMode = _
Replace) As Boolean
' This procedure inserts text specified by the strNewText
' argument into the Range object specified by the rngRange
' argument. It calls the IsLastCharParagraph procedure to
' strip off trailing paragraph marks from the rngRange object.
Call IsLastCharParagraph(rngRange, True)
With rngRange
Select Case intInsertMode
Case 0 ' Insert before text in range.
.InsertBefore strNewText
Case 1 ' Insert after text in range.
.InsertAfter strNewText
Case 2 ' Replace text in range.
.Text = strNewText
Case Else
End Select
InsertTextInRange = True
End With
End Function
Note The IsLastCharParagraph procedure is used to strip off any final paragraph marks before inserting text in the range. The IsLastCharParagraph procedure is discussed earlier.
See Also
Working with Microsoft Word Objects | The Range Object | Creating, Defining, and Redefining a Range, | Working with Text in a Range Object | Determining Where the Range Is Located | Understanding Paragraph Marks | The Selection Object