Reputation: 4760
I have an older project where I want to open a Word document and execute search and replace on it. It worked before when I had older Visual Studio and Office but now I have problems in VS 2012 (with Office 2013 installed).
I reference "Microsoft Word 15.0 Object Library" COM reference and I get 3 dll files:
Microsoft.Office.Core
Microsoft.Office.Interop.Word
VBIDE
My minimal test code:
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);
This code runs and the document gets opened, but then this exception occurs:
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
What is going on? I have an additional question: if I use v15.0 of Interop assembly (I suppose that came with my Office 2013), will the same code work on machines with previous versions of Word installed - let's say Office 2010?
Upvotes: 4
Views: 12009
Reputation: 15261
Before replacing text in the document, change ReadOnly to false in this line:
Word.Document aDoc = wordApp.Documents.Open(
ref fileName, ReadOnly: true, Visible: true);
Upvotes: 5