Word 文書を開いて検索と置換を実行したい古いプロジェクトがあります。古い Visual Studio と Office を使用していたときは機能していましたが、現在は VS 2012 (Office 2013 がインストールされている) で問題が発生しています。
「Microsoft Word 15.0 Object Library」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 としましょう) で同じコードが機能しますか?