【发布时间】:2013-10-22 03:40:28
【问题描述】:
我正在尝试使用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 本身中运行这个宏时,没有问题。
【问题讨论】:
-
您需要告诉 Excel 宏在哪个工作簿中。请参阅 Application.Run 的帮助
-
@TimWilliams:对不起。刚看到你的评论。删除了我的帖子。
-
@SiddharthRout - 你应该离开你的帖子!我懒得发布答案....
-
@TimWilliams:但现在你可以……懒惰?这只是一行:p
-
...蹩脚的ipad键盘...