4

我正在尝试使用C# 4.5. 我的 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.xlsDestination.xslx. 当我自己运行这个宏时Excel,没有问题。

4

1 回答 1

8
book.Run ("'Macros.xls'!MacroName");
于 2013-10-22T04:19:33.413 回答