2013-06-28 40 views
4

我有一個較舊的項目,我想打開一個Word文檔並執行搜索並替換它。它以前工作過,當我有較舊的Visual Studio和Office,但現在我在VS 2012(與Office 2013安裝)的問題。通過.NET自動化在Word文檔中搜索和替換

我引用 「的Microsoft Word 15.0對象庫」 COM參考,我得到3 dll文件:

Microsoft.Office.Core 
Microsoft.Office.Interop.Word 
VBIDE 

我最小的測試代碼:

using Word = Microsoft.Office.Interop.Word; 

... 

object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.doc"); 

Word.Application wordApp = new Word.Application { Visible = true };       

Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: true, Visible: true); 

aDoc.Activate(); 

Word.Find fnd = wordApp.ActiveWindow.Selection.Find; 

fnd.ClearFormatting(); 
fnd.Replacement.ClearFormatting(); 
fnd.Forward = true; 
fnd.Wrap = Word.WdFindWrap.wdFindContinue;        

fnd.Text = "aaa"; 
fnd.Replacement.Text = "bbb"; 

fnd.Execute(Replace: Word.WdReplace.wdReplaceAll); 

運行此代碼和文檔被打開,但隨後發生此異常:

System.Runtime.InteropServices.COMException was unhandled 
HelpLink=wdmain11.chm#37373 
HResult=-2146823683 
Message=This command is not available. 
Source=Microsoft Word 
ErrorCode=-2146823683 
StackTrace: 
    at Microsoft.Office.Interop.Word.Find.Execute(Object& FindText, Object& MatchCase, Object& MatchWholeWord, Object& MatchWildcards, Object& MatchSoundsLike, Object& MatchAllWordForms, Object& Forward, Object& Wrap, Object& Format, Object& ReplaceWith, Object& Replace, Object& MatchKashida, Object& MatchDiacritics, Object& MatchAlefHamza, Object& MatchControl) 
    at WordTest.MainForm.btnLaunchWord_Click(Object sender, EventArgs e) in c:\Work\Repos\WordTest\WordTest\Form1.cs:line 38 

發生了什麼事?我還有一個問題:如果我使用Interop程序集的v15.0(我想這是與我的Office 2013一起提供的),那麼相同的代碼是否可以在安裝了以前版本的Word的計算機上運行 - 比如說Office 2010?

回答

5

之前在文檔中替換文本,在這條線上只讀更改爲false:

Word.Document aDoc = wordApp.Documents.Open(
    ref fileName, ReadOnly: true, Visible: true); 
+0

THANK YOU!我從來沒有猜到...因爲同樣的事情工作多年,現在突然他們改變它更嚴格,我猜... – davidhq

+1

+此文件不應該是隻讀的。 ReadOnly: 可選對象。如需以只讀方式打開文檔。注意此參數不覆蓋保存文檔上的只讀建議設置。例如,如果文檔已經以只讀推薦開啓的方式保存,則將ReadOnly參數設置爲False不會導致文件以讀/寫方式打開。 – koprinkov

+0

謝謝你們!只需要在文件系統中檢查文件不是隻讀的! – CrazyTim