Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when calling Excel macro from C#

Tags:

c#

excel

vba

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:

Macro Security

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.

like image 517
rhughes Avatar asked Feb 15 '23 22:02

rhughes


1 Answers

book.Run ("'Macros.xls'!MacroName");
like image 187
Tim Williams Avatar answered Feb 23 '23 08:02

Tim Williams