Search code examples
c#vbams-wordoffice-interopoffice-automation

C# ambiguity error on Document.Close() when converting VBA macro to C#


The Word VBA macro that I am converting to C# has the following line. I am very specifically using the Close() method on the Document object. I have not found any question that exactly answers my question below. There are similar questions, such as this one: Compile time warning when using 'Microsoft.Office.Interop.Word._Document.Close'

But looking at it I was not able to figure out the exact cast I have to use.

ActiveDocument.Close wdDoNotSaveChanges

I converted this to C# like this:

using Microsoft.Office;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;

Object oMissing = System.Reflection.Missing.Value;
Word.Document oWordDoc = new Word.Document();

oWordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges, oMissing, oMissing);

However at the last line I get the following ambiguity error:

Ambiguity between method 'Microsoft.Office.Interop.Word._Document.Close(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.DocumentEvents2_Event.Close'. Using method group.

Obviously I can't rename the Close method of Word (I guess), so I tried to cast my oWordDoc but nothing seems to work.

Can someone shed some light on it how to do this right? Thank you.


Solution

  • Cast it to Microsoft.Office.Interop.Word._Document, which does not contain that event.

    ((Microsoft.Office.Interop.Word._Document)oWordDoc).Close(Word.WdSaveOptions.wdDo‌​NotSaveChanges, oMissing, oMissing);