共用方式為


以程式設計方式定義並選取文件中的範圍

您也可以使用 Range 物件定義 Microsoft Office Word 文件中的範圍。 您可以透過多種方式選擇整個文件,例如,使用 Range 物件的 Select 方法,或使用 Document 類別的 Content 屬性 (在文件層級自訂中) 或 Document 類別 (在 VSTO 增益集中)。

適用對象:本主題資訊適用於文件層級的專案和 Word 的 VSTO 增益集專案。 如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能

定義範圍

下列範例示範如何建立包含使用中文件中前七個字元 (包括非列印字元) 的新 Range 物件。 它接著會選取範圍內的文字。

定義文件層級自訂中的範圍

  1. 將開始和結束字元傳遞給 Document 類別的 Range 方法,以將範圍新增至文件。 若要使用此程式碼範例,請從專案的 ThisDocument 類別中執行它。

    object start = 0; 
    object end = 7; 
    Word.Range rng = this.Range(ref start, ref end); 
    
    rng.Select();
    

使用 VSTO 增益集定義範圍

  1. 將開始和結束字元傳遞給 Document 類別的 Range 方法,以將範圍新增至文件。 下列程式碼範例會將範圍新增至使用中文件。 若要使用此程式碼範例,請從專案的 ThisAddIn 類別中執行它。

    Word.Range rng = this.Application.ActiveDocument.Range(0, 7);
    
    rng.Select();
    

選取文件層級自訂中的範圍

下列範例示範如何使用 Range 物件的 Select 方法或使用 Document 類別的 Content 屬性來選取整份文件。

使用 Select 方法將整份文件選取為範圍

  1. 使用包含整份文件之 RangeSelect 方法。 若要使用下列程式碼範例,請從專案的 ThisDocument 類別中執行此範例。

    object start = this.Content.Start;
    object end = this.Content.End;
    
    this.Range(ref start, ref end).Select();
    

使用內容屬性將整份文件選取為範圍

  1. 使用 Content 屬性定義包含整份文件的範圍。

    this.Content.Select();
    

    您也可以使用其他物件的方法和屬性來定義範圍。

選取使用中文件中的句子

  1. 使用 Sentences 集合設定範圍。 使用您想要選取之句子的索引。

    Word.Range s2 = this.Sentences[2]; 
    s2.Select();
    

    另一種選取句子的方法是手動設定範圍的開始和結束值。

手動設定開始和結束值來選取句子

  1. 建立範圍變數。

    Word.Range rng;
    
  2. 檢查文件中是否至少有兩個句子,設定範圍的 StartEnd 引數,然後選取範圍。

    if (this.Sentences.Count >= 2) 
    {
        object startLocation = this.Sentences[2].Start; 
        object endLocation = this.Sentences[2].End; 
    
        // Supply a Start and End value for the Range. 
        rng = this.Range(ref startLocation, ref endLocation); 
    
        // Select the Range.
        rng.Select();
    }
    

使用 VSTO 增益集選取範圍

下列範例示範如何使用 Range 物件的 Select 方法或使用 Document 類別的 Content 屬性來選取整份文件。

使用 Select 方法將整份文件選取為範圍

  1. 使用包含整份文件之 RangeSelect 方法。 下列程式碼範例會選取使用中文件的內容。 若要使用此程式碼範例,請從專案的 ThisAddIn 類別中執行它。

    this.Application.ActiveDocument.Range(
        this.Application.ActiveDocument.Content.Start,
        this.Application.ActiveDocument.Content.End).Select();
    

使用內容屬性將整份文件選取為範圍

  1. 使用 Content 屬性定義包含整份文件的範圍。

    this.Application.ActiveDocument.Content.Select();
    

    您也可以使用其他物件的方法和屬性來定義範圍。

選取使用中文件中的句子

  1. 使用 Sentences 集合設定範圍。 使用您想要選取之句子的索引。

    Word.Range s2 = this.Application.ActiveDocument.Sentences[2];
    s2.Select();
    

    另一種選取句子的方法是手動設定範圍的開始和結束值。

手動設定開始和結束值來選取句子

  1. 建立範圍變數。

    Word.Range rng;
    
  2. 檢查文件中是否至少有兩個句子,設定範圍的 StartEnd 引數,然後選取範圍。

    Word.Document document = this.Application.ActiveDocument;
    
    if (document.Sentences.Count >= 2)
    {
        object startLocation = document.Sentences[2].Start;
        object endLocation = document.Sentences[2].End;
    
        // Supply a Start and End value for the Range. 
        rng = document.Range(ref startLocation, ref endLocation);
    
        // Select the Range.
        rng.Select();
    }