I have an older project where I want to open a Word document and search and replace it. It worked earlier when I had older Visual Studio and Office, but now I have problems with VS 2012 (with Office 2013 installed).
I link to the COM link "Microsoft Word 15.0 Object Library" and get 3 DLL files:
Microsoft.Office.Core Microsoft.Office.Interop.Word VBIDE
My minimum 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 opens, 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's happening? I have an additional question: if I use the Interop build v15.0 (I believe I came with my Office 2013), will the same code work on machines with previous versions of Word - say, Office 2010?