c# - 按字符串选择范围

标签 c# office-interop

如何更改此功能,以便在 word 文档中选择字符“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();

}

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

谢谢

最佳答案

需要传递文档中你希望范围覆盖的位置,见: 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等

关于c# - 按字符串选择范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2989194/

相关文章:

c# - 我如何比较 "reference equality"的 Word Interop 对象并确定某个段落所属的集合或父对象?

c# - 分发需要 Microsoft.Office.Interop.Excel 的应用程序

c# - 尝试使用 Excel 2007 进行办公自动化,但一直使用 Excel 2003

c# - 表单已经关闭时调用时出错

c# - 使用 TcpClient/Socket 安全传输/发送大数据包

c# - 应用程序崩溃

c# - 用于 SMB 文件共享的 S3 API

c# - 在 Word 文档中编辑 Excel 电子表格对象(C# Interop)

c# - 无法在 Excel 中的 "Want to save your changes"对话框后补漏白

c# - 在 C# .NET 中清理 ODBC DSN