2013-01-10 41 views
4

我有一個文本文件,其中有一個文本框。當我運行自動查找並替換主文檔中的匹配項,但不匹配文本框中的任何內容。我如何告訴查找和替換功能以包含文本框。Word自動查找並替換不包括文本框

Word.Range range = objDoc.Content; 

object findtext = Field; 
object findreplacement = Value; 
object findwrap = WdFindWrap.wdFindContinue; 
object findreplace = WdReplace.wdReplaceAll; 

range.Find.Execute(findtext, missing, missing, missing, missing, missing, missing, findwrap, missing, findreplacement, findreplace); 

我懷疑我需要更改range = objDoc.content行。

+1

入住這個地方了http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/36cebc60-7c7e-494c-ad2d-0dcebce5a706/ 在搜索的過程中給出了一些答案文本框,檢查,看看它不是'主要故事'的一部分 – RhysW

回答

5

稍顯凌亂,但這個工作對我來說:

using System.Runtime.InteropServices; 
using Microsoft.Office.Interop.Word; 

namespace ConsoleApplication7 
{ 
    class Program 
    { 
     static void Main() 
     { 
      const string documentLocation = @"C:\temp\Foo.docx"; 
      const string findText = "Foobar"; 
      const string replaceText = "Woo"; 

      FindReplace(documentLocation, findText, replaceText); 
     } 

     private static void FindReplace(string documentLocation, string findText, string replaceText) 
     { 
      var app = new Application(); 
      var doc = app.Documents.Open(documentLocation); 

      var range = doc.Range(); 

      range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText); 

      var shapes = doc.Shapes; 

      foreach (Shape shape in shapes) 
      { 
       var initialText = shape.TextFrame.TextRange.Text; 
       var resultingText = initialText.Replace(findText, replaceText); 
       shape.TextFrame.TextRange.Text = resultingText; 
      } 

      doc.Save(); 
      doc.Close(); 

      Marshal.ReleaseComObject(app); 
     } 
    } 
} 

前:

Before

後:

After

+0

偉大的 - 花費年齡試圖找出文本框居住的地方。 「doc.Shapes」是一個勝利者。 – xan

+1

順便說一句,您仍然可以在TextFrame的範圍上使用Find。它只是一個單獨的電話。只是有點煩人。 – Chris

+0

@Chris gotcha,很高興知道! – JMK

-1

此解決方案不替換文本無線在頭文件中的文本框很薄。