Automating a Word Macro from C#

F

fatima.issawi

Hello,

I am trying to run a Word Macro from C#. I am getting the error:

Unknown name. (Exception from HRESULT: 0x80020006
(DISP_E_UNKNOWNNAME))

when I get to the line that actually runs the macro. All the other
code runs correctly. Am I calling the macro correctly? The macro is
available in the Normal.dot template. It is available if I open the
file and manually try to run the macro. It just fails when I try to
automate it.

I have attached a code snippet. Any help is appreciated.

Thanks,
Fatima

*********************************************************************************
// Run Macros to fix up the document and save the file as a .DOC file
Type wordType = Type.GetTypeFromProgID("Word.Application");
object wordApplication = Activator.CreateInstance(wordType);

wordType.InvokeMember("Visible",
System.Reflection.BindingFlags.SetProperty, null, wordApplication,
new object[]
{ true });
object wordDocuments = wordType.InvokeMember("Documents",
System.Reflection.BindingFlags.GetProperty,
null,
wordApplication, null);
object wordDocument = wordDocuments.GetType().InvokeMember("Open",
System.Reflection.BindingFlags.InvokeMethod,
null,
wordDocuments, new object[] { exportedFile.ToString() });

// Run Macros on the document to fix it up.
wordDocument.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.InvokeMethod,
null,
wordDocument, new object[] { "Test" });

// Save the document as a .DOC file.
wordDocument.GetType().InvokeMember("SaveAs",
System.Reflection.BindingFlags.InvokeMethod,
null,
wordDocument, new object[] { savedFile, fileFormat });
 
F

fatima.issawi

Hello,

Silly me. I should be calling the macro like this instead:

wordApplication.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.InvokeMethod,
null,
wordApplication, new object[] { "Test" });

Hope this helps someone else.

Regards,
Fatima
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top