2010-06-07 74 views
1

如何更改此功能,以便在字符「E」和「F」之間選擇字符文檔中的字符範圍(如果有); xasdasdEcdscasdcFvfvsdfv被強調到我的範圍 - > cdscasdc按字符串選擇範圍

private void Rango() 
{ 
Word.Range rng; 

Word.Document document = this.Application.ActiveDocument; 

object startLocation = "E"; 
object endLocation = "F"; 

// Supply a Start and End value for the Range. 
rng = document.Range(ref startLocation, ref endLocation); 

// Select the Range. 
rng.Select(); 

} 

此功能不會讓我引用字符串類型的兩個對象通過.......

感謝

回答

7

您需要通過你想覆蓋的範圍在文檔中的位置,請參閱: How to: Define and Select Ranges in Documents

我加入了下面的一些示例代碼:

var word = new Microsoft.Office.Interop.Word.Application(); 

string document = null; 
using (OpenFileDialog dia = new OpenFileDialog()) 
{ 
    dia.Filter = "MS Word (*.docx)|*.docx"; 
    if (dia.ShowDialog() == DialogResult.OK) 
    { 
     document = dia.FileName; 
    } 
}   

if (document != null) 
{ 
    Document doc = word.Documents.Open(document, ReadOnly: false, Visible: true); 
    doc.Activate(); 
    string text = doc.Content.Text; 

    int start = text.IndexOf('E') + 1; 
    int end = text.IndexOf('F'); 
    if (start >= 0 && end >= 0 && end > start) 
    { 
     Range range = doc.Range(Start: start, End: end); 
     range.Select(); 
    } 
} 

不要忘記關閉文檔和Word等