我有一个较旧的项目,我想在其中打开Word文档并执行搜索和替换。它之前我有较旧的Visual Studio和Office,但现在我在VS 2012中遇到了问题(安装了Office 2013)。
我引用“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
发生了什么事?我还有一个问题:如果我使用V10.0的Interop程序集(我想我的Office 2013附带),相同的代码是否可以在安装了以前版本的Word的机器上运行 - 比方说Office 2010?
答案 0 :(得分:5)
在替换文档中的文本之前,请在此行中将ReadOnly更改为false:
Word.Document aDoc = wordApp.Documents.Open(
ref fileName, ReadOnly: true, Visible: true);