通过 C# 互操作执行 VBA 宏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/428842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute VBA Macro via C# Interop?
提问by Jon Artus
just wondering if anyone could suggest why I might be getting an error? I'm currently trying to execute a macro in a workbook by calling the Application.Run method that the interop exposes.
只是想知道是否有人可以建议为什么我可能会收到错误?我目前正在尝试通过调用互操作公开的 Application.Run 方法在工作簿中执行宏。
It's currently throwing the following COM Exception:
它目前抛出以下 COM 异常:
{System.Runtime.InteropServices.COMException (0x800A03EC): Cannot run the macro Macro1'.
The macro may not be available in this workbook or all macros may be disabled.
I've put the containing workbook in a trusted location, set all of the security settings to their minimum values, and trusted programmatic access to my object model. I'm entirely out of ideas and Google's failed me so far!
我已将包含的工作簿放在受信任的位置,将所有安全设置设置为其最小值,并信任对我的对象模型的编程访问。我完全没有想法,谷歌到目前为止让我失望!
Has anyone done this, or can you suggest anything which I could try?
有没有人做过这个,或者你能建议我可以尝试的任何东西吗?
Many thanks!
非常感谢!
采纳答案by Jon Artus
It turned out that there were actually two identically-named macros which had been injected into the workbook. The exception above translates to a "Compile Error: Ambiguous name detected" error in VBA - I should have gone straight into VBA to look at this, rather than assuming that something odd was happening with the interop.
结果发现实际上有两个同名的宏被注入到工作簿中。上面的异常转化为 VBA 中的“编译错误:检测到模糊名称”错误 - 我应该直接进入 VBA 来查看这个,而不是假设互操作发生了一些奇怪的事情。
回答by nano
Although this is already answered, Ive had the SAME symptoms. Finally, ive resolved the problem with this hotfix of Microsoft
虽然这已经得到回答,但我也有同样的症状。最后,我用微软的这个修补程序解决了这个问题
回答by Swab.Jat
I ran into same issue, Macro is stored in a "Module" named "MainModule".
我遇到了同样的问题,宏存储在名为“MainModule”的“模块”中。
I tried
我试过
App.Run("Abc.xlsm!CalcSomething");
App.Run("MainModule!CalcSomething");
App.Run("Abc.xlsm.CalcSomething");
App.Run("MainModule.CalcSomething");
App.Run("CalcSomething);
Nothing worked.
没有任何效果。
回答by Fionnuala
If the macro is stored in the personal workbook, you may have to reference the workbook name: personal.xls!macroname
如果宏存储在个人工作簿中,您可能需要引用工作簿名称:personal.xls!macroname