从C#调用Excel宏时出错 [英] Error when calling Excel macro from C#
本文介绍了从C#调用Excel宏时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用 C#4.5
从Excel文件中调用宏。我的Excel版本是2010年。
当我尝试调用宏时,我收到以下错误:
无法运行宏MacroName。此工作簿中的宏可能不可用,或者所有宏都可能被禁用。
我已经google了很多,但没有什么真的似乎有效。
我已经打开了宏安全性,如下面的屏幕截图所示:
Excel.Application book = null;
Excel.Workbooks workbooks = null;
Excel.Workbook macroWorkbook = null;
Excel.Workbook destinationWorkbook = null;
try
{
book = new Excel.Application();
工作簿= 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; //最终将在执行之前抛出
}
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
中运行此宏时,没有问题。
解决方案
pre> book.Run('Macros.xls'!MacroName);
I am trying to call a macro from an Excel file using C# 4.5
. My Excel version is 2010.
When I try to call the macro, I get the following error:
Cannot run the macro 'MacroName'. The macro may not be available in this workbook or all macros may be disabled.
I have googled a lot for this, but nothing really seems to work.
I have opened up macro security, as the following screen shot shows:
The code I am using is as follows:
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;
}
The actual macro is stored in Macros.xls
and will run on the Destination.xslx
. When I run this macro in Excel
itself, there is no problem.
解决方案
book.Run ("'Macros.xls'!MacroName");
这篇关于从C#调用Excel宏时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文