调用从C#Excel宏时出错 [英] Error when calling Excel macro from C#
本文介绍了调用从C#Excel宏时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想打电话给使用 C#4.5
从Excel文件中的宏。我的Excel版本是2010
当我尝试调用宏,我得到以下错误:
无法运行宏宏名。宏可能无法在此工作簿中可用或者所有的宏可能被禁用。
我GOOGLE了很多关于这一点,但没有什么似乎工作。
我已经打开了宏安全性,如下面的屏幕截图显示:
我使用的代码如下:
Excel.Application书= NULL;
Excel.Workbooks工作簿= NULL;
Excel.Workbook macroWorkbook = NULL;
Excel.Workbook destinationWorkbook = NULL;
试
{
=书新Excel.Application();
=工作簿book.Workbooks;
macroWorkbook = workbooks.Open(@D:\Work\Macros.xls);
destinationWorkbook = workbooks.Open(@D:\Work\Destination.xlsx);
book.Run(宏名);
macroWorkbook.Close(假);
destinationWorkbook.Close(真);
}
赶上(异常前)
{
罚球前; //最终在此之前将被执行时抛出
}
终于
{
book.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(macroWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(destinationWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(练习册);
System.Runtime.InteropServices.Marshal.ReleaseComObject(书);
macroWorkbook = NULL;
destinationWorkbook = NULL;
工作簿= NULL;
书= NULL;
}
实际宏存储在 Macros.xls
,并在 Destination.xslx
运行。当我运行在 Excel中
本身这个宏,是没有问题的。
解决方案
book.Run('Macros.xls宏名!);
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屋!
查看全文