我正在尝试使用C# 4.5
从Excel文件中调用宏。我的Excel版本是2010年。
当我尝试调用宏时,出现以下错误:
Cannot run the macro 'MacroName'. The macro may not be available in this workbook or all macros may be disabled.
我为此搜索了很多内容,但似乎没有任何效果。
我打开了宏安全性,如下面的屏幕截图所示:
我使用的代码如下:
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.xls
中,并将在Destination.xslx
上运行。当我在Excel
本身运行此宏时,没有问题。
答案 0 :(得分:8)
book.Run ("'Macros.xls'!MacroName");