Compartilhar via


How to: Programmatically reset ranges in Word documents

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Use the SetRange method to resize an existing range in a Microsoft Office Word document.

Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Word. For more information, see Features available by Office application and project type.

To reset an existing range

  1. Set an initial range starting with the first seven characters in the document.

    The following code example can be used in a document-level customization.

    Dim rng As Word.Range = Me.Range(Start:=0, End:=7)
    
    object start = 0; 
    object end = 7; 
    Word.Range rng = this.Range(ref start,ref end);
    

    The following code example can be used in a VSTO Add-in. This code uses the active document.

    Dim rng As Word.Range = Me.Application.ActiveDocument.Range(Start:=0, End:=7)
    
    Word.Range rng = this.Application.ActiveDocument.Range(0, 7);
    
  2. Use SetRange to start the range at the second sentence and end it at the end of the fifth sentence.

    rng.SetRange(Start:=Me.Sentences(2).Start, End:=Me.Sentences(5).End)
    
    rng.SetRange(this.Sentences[2].Start, this.Sentences[5].End);
    

Document-Level Customization Example

To reset an existing range in a document-level customization

  1. The following example shows the complete example for a document-level customization. To use this code, run it from the ThisDocument class in your project.

    Dim rng As Word.Range = Me.Range(Start:=0, End:=7)
    
    ' Reset the existing Range.
    rng.SetRange(Start:=Me.Sentences(2).Start, End:=Me.Sentences(5).End)
    rng.Select()
    
    object start = 0; 
    object end = 7; 
    Word.Range rng = this.Range(ref start,ref end); 
    
    // Reset the existing Range. 
    rng.SetRange(this.Sentences[2].Start, this.Sentences[5].End); 
    rng.Select();
    

VSTO Add-in example

To reset an existing range in a VSTO Add-in

  1. The following example shows the complete example for a VSTO Add-in. To use this code, run it from the ThisAddIn class in your project.

    Dim rng As Word.Range = Me.Application.ActiveDocument.Range(Start:=0, End:=7)
    
    ' Reset the existing Range.
    rng.SetRange(Start:=Me.Application.ActiveDocument.Sentences(2).Start, _
        End:=Me.Application.ActiveDocument.Sentences(5).End)
    rng.Select()
    
    Word.Range rng = this.Application.ActiveDocument.Range(0, 7);
    
    // Reset the existing Range. 
    rng.SetRange(this.Application.ActiveDocument.Sentences[2].Start,
        this.Application.ActiveDocument.Sentences[5].End);
    rng.Select();
    

See also