4

我有一个较旧的项目,我想在其中打开一个 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

到底是怎么回事?我还有一个问题:如果我使用 v15.0 的 Interop 程序集(我想我的 Office 2013 附带),相同的代码是否可以在安装了以前版本的 Word 的机器上工作 - 比如 Office 2010?

4

1 回答 1

5

在替换文档中的文本之前,在此行中将 ReadOnly 更改为 false:

Word.Document aDoc = wordApp.Documents.Open(
    ref fileName, ReadOnly: true, Visible: true);
于 2013-06-28T22:12:53.993 回答