2017-06-15 136 views
0

下面的代碼能夠找到我正在查找的文本,但是當我去替換它時,文本不會被替換。我沒有得到任何例外。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. 保存並更新代碼中的文件路徑。

回答

0

代碼是工作的罰款,我是混合formfields和普通文本和「查找和替換」功能,MS-Word提供了無法,充分合作(再有人能找到它,而不是替代它)。

0

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