I am trying to call a macro from an Excel file using C# 4.5. My version of Excel is 2010.
When I try to call a 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 searched a lot for this, but nothing really works.
I opened macro security, as shown in the following screenshot:

The code I use 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;
}
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 saved in Macros.xlsand will work on Destination.xslx. When I run this macro in itself Excel, there is no problem.
source
share