C# Word Interop - "Find and replace" 找到单词但不替换它

C# Word Interop - "Find and replace" finds word but does not replace it

下面的代码能够找到我要找的文本,但是当我去替换它时,文本并没有被替换。我没有例外。

var word = new Application();
File.Delete(@"Your new test document.docx");
File.Copy(@"Your test document.docx", @"Your new test document.docx");
var document = word.Documents.Open(@"Your new test document.docx");
document.Activate();

while (document.Content.Find.Execute(FindText: "([Tag"))
{
    var stringToReplace = document.Content.Text.Substring(document.Content.Text.IndexOf("([Tag"), document.Content.Text.IndexOf("])") + 2 - document.Content.Text.IndexOf("([Tag"));
    var replacement = stringToReplace.Replace("(", "").Replace(")", "");

    if (document.Content.Find.Execute(FindText: stringToReplace))
    {
        Console.WriteLine(stringToReplace);
        document.Content.Find.Execute(FindText: stringToReplace, ReplaceWith: replacement, Replace: WdReplace.wdReplaceOne);
    }
    else
        Console.WriteLine("Failed");
}

document.Close(true);
word.Quit();
Marshal.ReleaseComObject(document);
Marshal.ReleaseComObject(word);
Console.WriteLine("Done");
Console.ReadLine();

测试代码:

  1. 创建 word 文档。
  2. 将以下内容粘贴到其中:

    ([标记名字] [标记姓氏])

    地址编号:2

    计算器

    拥有那辆 rad 汽车的教皇被命名为 ([Tag FirstName], [Tag LastName])

  3. 在代码中保存和更新文件路径。

documentation 使用此示例进行替换

private void SearchReplace()
{
    Word.Find findObject = Application.Selection.Find;
    findObject.ClearFormatting();
    findObject.Text = "find me";
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = "Found";

    object replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}

您会注意到它声明了 replaceAll = Word.WdReplace.wdReplaceAll,然后将其传递给 findObject.Execute,而您传递的 WdReplace.wdReplaceOne 只会替换找到的第一个项目。

代码运行良好,我将表单域和普通文本混合在一起,而 ms-word 提供的 "Find and replace" 功能无法与之完全兼容(它再次能够找到它,但不能替换它)。