This documentation is archived and is not being maintained.

How to: Collapse Ranges or Selections in Documents

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

If you are working with a Range or Selection object, you might want to change the selection to an insertion point before inserting text, to avoid overwriting existing text. Both the Range and Selection objects have a Collapse method, which makes use of two WdCollapseDirection enumerations:

  • wdCollapseStart- collapses the selection to the beginning of the selection. This is the default if you do not specify an enumeration.

  • wdCollapseEnd - collapses the selection to the end of the selection.

To collapse a range and insert new text

  1. Create a Range object consisting of the first paragraph in the document.

    Dim rng As Word.Range = Me.Paragraphs(1).Range
    
    
  2. Use the wdCollapseStart enumeration to collapse the range.

    rng.Collapse(Word.WdCollapseDirection.wdCollapseStart)
    
    
  3. Insert the new text.

    rng.Text = " New Text "
    
    
  4. Select the Range.

    rng.Select()
    
    

If you use the wdCollapseEnd enumeration, the text is inserted at the beginning of the following paragraph.

rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)

You might expect that inserting a new sentence would insert it before the paragraph marker, but that is not the case because the original range includes the paragraph marker. For more information, see How to: Exclude Paragraph Marks When Creating Ranges.

The following example shows the complete method.

Example

Dim rng As Word.Range = Me.Paragraphs(1).Range

rng.Collapse(Word.WdCollapseDirection.wdCollapseStart)

rng.Text = " New Text "
rng.Select()

See Also

Show: