I am trying to call a macro from an Excel file using C# 4.5
. My Excel version is 2010.
When I try to call the macro, I get the following error:
Cannot run the macro 'MacroName'. The macro may not be available in this workbook or all macros may be disabled.
I have googled a lot for this, but nothing really seems to work.
I have opened up macro security, as the following screen shot shows:
The code I am using is as follows:
Excel.Application book = null;
Excel.Workbooks workbooks = null;
Excel.Workbook macroWorkbook = null;
Excel.Workbook destinationWorkbook = null;
try
{
book = new Excel.Application();
workbooks = book.Workbooks;
macroWorkbook = workbooks.Open(@"D:\Work\Macros.xls");
destinationWorkbook = workbooks.Open(@"D:\Work\Destination.xlsx");
book.Run("MacroName");
macroWorkbook.Close(false);
destinationWorkbook.Close(true);
}
catch (Exception ex)
{
throw ex; // the finally will be executed before this is thrown
}
finally
{
book.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(macroWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(destinationWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
macroWorkbook = null;
destinationWorkbook = null;
workbooks = null;
book = null;
}
The actual macro is stored in Macros.xls
and will run on the Destination.xslx
. When I run this macro in Excel
itself, there is no problem.
book.Run ("'Macros.xls'!MacroName");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With