C#Word Interop - “查找并替换”查找单词但不替换它

问题描述:

下面的代码能够找到我正在查找的文本,但是当我去替换它时,文本不会被替换。我没有得到任何例外。C#Word Interop - “查找并替换”查找单词但不替换它

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

    #1

    谁拥有教皇是RAD车名称([Tag FirstName],[Tag LastName])

  3. 保存并更新代码中的文件路径。

代码是工作的罚款,我是混合formfields和普通文本和“查找和替换”功能,MS-Word提供了无法,充分合作(再有人能找到它,而不是替代它)。

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只会替换找到的第一个项目。

+0

目标是一次只更换一个,以便部分正常。我在另一个区域也有几乎相同的(相同的替换代码,但是不同的场景)代码,并且实际上起作用。我确实尝试了你发布的代码,但仍然没有运气。 – MarcusRB