按字符串选择范围

时间:2010-06-07 11:57:06

标签: c# office-interop

如何更改此功能,以便选择字符“E”和“F”之间的word文档中的字符范围(如果有); 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();

}

这个函数不允许我通过引用传递两个字符串类型的对象.......

由于

1 个答案:

答案 0 :(得分: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等。