简体   繁体   English

在C#中运行Excel宏在特定工作簿中失败

[英]Running Excel macro in a specific workbook fails from C#

I'm trying to run a macro in an Excel workbook from C# using the standard Microsoft.Office.Interop.Excel library. 我正在尝试使用标准的Microsoft.Office.Interop.Excel库在C#的Excel工作簿中运行宏。 In my scenario the version of Excel could be either 2010 or 2013. 在我的场景中,Excel的版本可以是2010年或2013年。

There could be multiple workbooks open for the same Application object, each potentially with the same macro names, so I'm explicitly passing in the workbook name 可能有多个工作簿为同一个Application对象打开,每个工作簿可能具有相同的宏名称,因此我明确地传入工作簿名称

string macro = string.Format("{0}!{1}", workbook.Name, macroName);
Application.Run(macro);

Weirdly, I get a COMException if the workbook name has hyphens in it: 奇怪的是,如果工作簿名称中包含连字符,则会出现COMException:

Application.Run("My-Workbook!macro1")

But runs fine without hyphens: 但运行正常没有连字符:

Application.Run("MyWorkbook!macro1")

Is it just me or is this weird? 这只是我还是这很奇怪? Can anyone think of a workaround? 谁能想到一个解决方法?

Wrap the workbook name in quotes 将工作簿名称包含在引号中

string macro = string.Format("'{0}'!{1}", workbook.Name, macroName);
Application.Run(macro);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM