【问题标题】:Run VBA macro in Excel sheet using external c# console application使用外部 c# 控制台应用程序在 Excel 工作表中运行 VBA 宏
【发布时间】:2015-09-20 21:37:51
【问题描述】:

我正在尝试调用 Excel 文件中的一个宏。 下面是我得到的代码,但是在下面运行时会抛出异常,并显示以下消息。

代码:

// Define your Excel Objects
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = null;

try
{
    //Start Excel and open the workbook.
    xlWorkBook = xlApp.Workbooks.Open(@"C:\MyFolder\Junk\macro\xxxxxReport.xlsm");

    //Run the macros by supplying the necessary arguments
    xlApp.Run("LookupHLink");

    //xlWorkBook.Save();
    //Clean-up: Close the workbook
    xlWorkBook.Close(false);

    //Quit the Excel Application
    xlApp.Quit();
}
catch (Exception ex)
{
}
finally
{
    //~~> Clean Up
    releaseObject(xlApp);
    releaseObject(xlWorkBook);
}

宏没有参数。

Public Sub LookupHLink()

错误信息:

无法运行宏“LookupHLink”。该工作簿中的宏可能不可用,或者所有宏都可能被禁用。

如果我做错了什么,请告诉我。

【问题讨论】:

  • sub 是在常规模块中还是在 Sheet 模块中?如果是后者,那么您可能需要使用(例如)xlApp.Run("Sheet1.LookupHLink");,其中Sheet1 是工作表模块的名称。
  • 也试过了,但又出错了:无法运行宏“XXXX_Detail.LookupHLink”。该工作簿中的宏可能不可用,或者所有宏都可能被禁用。

标签: c# excel vba


【解决方案1】:

据我所知,这个错误的可能原因是:

  • 系统找到文件但无法加载。
  • 文件已加载,但没有宏。
  • 文件已加载,但宏被禁用。
  • 文件已加载,宏存在...但您拼错了名称。

鉴于可用信息,似乎更可能的原因是禁用了宏。


您可以尝试将文件移动到受信任的位置:

您可以通过单击文件 > 选项来查看受信任的位置,然后 单击信任中心 > 信任中心设置 > 受信任位置。

见Change macro security settings in Excel [2010]。


您也可以尝试更改安全设置:

在 Excel 2007 中

  • 单击 Microsoft Office 按钮,然后单击 Excel 选项。
  • 点击信任中心。
  • 点击信任中心设置。
  • 点击宏设置。
  • 单击以选中“信任对 VBA 项目对象模型的访问”复选框。
  • 单击“确定”关闭“Excel 选项”对话框。

来源:You may receive an run-time error when you programmatically allow access to a Visual Basic project in Excel 2003 and in Excel 2007 - at Microsoft Knowledge base。


注意:C# 中的可选参数是一个相对较新的功能...您可以尝试旧方法并使用 Type.Missing 来填充 Run method 的臭名昭著的 30 个参数。像这样的:

xlApp.Run('macro', Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多