从C#调用Excelmacros时出错

我正在尝试使用C# 4.5从Excel文件中调用macros。 我的Excel版本是2010年。

当我尝试调用macros时,出现以下错误:

 Cannot run the macro 'MacroName'. The macro may not be available in this workbook or all macros may be disabled. 

我为此已经search了很多,但似乎没有任何工作。

我打开了macros观安全,如下面的屏幕截图所示:

宏安全

我正在使用的代码如下所示:

 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; } 

实际的macros存储在Macros.xls ,并将在Destination.xslx上运行。 当我在Excel本身运行这个macros,没有问题。

 book.Run ("'Macros.xls'!MacroName");