I am trying to call an Excel Macro from .Net. The macro is called DoKbTest and is stored in book1.xls
However when I run the code I get the following error "An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll. Additional information: Exception has been thrown by the target of an invocation. " when executing the RunMacro(oExcel, new Object[]{"DoKbTest"}); line. The macro works perfectly when called from excel.
Does anyone have any insight into why this might occur?
Thanks
(Code is from this link
However when I run the code I get the following error "An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll. Additional information: Exception has been thrown by the target of an invocation. " when executing the RunMacro(oExcel, new Object[]{"DoKbTest"}); line. The macro works perfectly when called from excel.
Does anyone have any insight into why this might occur?
Thanks
(Code is from this link
Code:
private void button5_Click(object sender, System.EventArgs e)
{
object oMissing = System.Reflection.Missing.Value;
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
oExcel.Visible = true;
Excel.Workbooks oBooks = oExcel.Workbooks;
Excel._Workbook oBook = null;
oBook = oBooks.Open("c:\\book1.xls", oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
// Run the macros.
RunMacro(oExcel, new Object[]{"DoKbTest"});
RunMacro(oExcel, new Object[]{"DoKbTestWithParameter",
"Hello from C# Client."});
// Quit Excel and clean up.
oBook.Close(false, oMissing, oMissing);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oBook);
oBook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject (oBooks);
oBooks = null;
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oExcel);
oExcel = null;
}
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);
}