从C#调用Excel宏时出错

时间:2013-10-22 03:40:29

标签: c# excel vba excel-vba

我正在尝试使用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.

我为此搜索了很多内容,但似乎没有任何效果。

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

Macro Security

我使用的代码如下:

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本身运行此宏时,没有问题。

1 个答案:

答案 0 :(得分:8)

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