1 out of 2 rated this helpful - Rate this topic

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.

    Word.Range rng = this.Paragraphs[1].Range; 
    
    
  2. Use the wdCollapseStart enumeration to collapse the range.

    object direction = Word.WdCollapseDirection.wdCollapseStart;
    rng.Collapse(ref direction); 
    
    
  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.

direction = Word.WdCollapseDirection.wdCollapseEnd;
rng.Collapse(ref direction);

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

Word.Range rng = this.Paragraphs[1].Range; 

object direction = Word.WdCollapseDirection.wdCollapseStart;
rng.Collapse(ref direction); 

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

See Also

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ