【问题标题】:Can I terminate VBA macro execution with a C# dll我可以使用 C# dll 终止 VBA 宏执行吗
【发布时间】:2020-10-11 17:12:38
【问题描述】:

在 VBA 中,我可以使用 End 语句终止宏的执行,如下所示。

Sub DoSomeThing()
    Dim test As Boolean
    test = false
    test = function()
    If test Then
        End 'Macro execution is terminated
    End if
End Sub

我希望我的 C# DLL 包含具有相同效果的方法?我正在考虑以下几点。

public void DoSomething_CSharp()
{
    var test = false;
    test = Function();
    if (test)
    {
        //Call a command here that terminates execution of the VBA macro that calls this method.
    }
}

我意识到End 是一个 VBA 语句,但我不知道如何从 C# DLL 中访问 VBA 语句。 (正如这个问题所示,我是 C# 新手。)

【问题讨论】:

  • 为什么不将布尔值返回到 VBA,然后从那里关闭?
  • 使用System.Environment.Exit(0);
  • 没有。您必须使用throw new Exception("Macro aborted"); 来完成。制定更好的消息来告诉您的用户您决定忽略他们的命令的原因取决于您。

标签: c# excel vba


【解决方案1】:

VBA 中的End 有什么作用?

  • 在 MS Access Runtime 中,它会中断执行并关闭应用程序。
  • 在其他 Office 应用程序(例如 Excel 或“非运行时”模式下的 Access)中,它会中断执行并通过调用堆栈回退到 UI 层。

由于您用“Excel”标记了您的问题,我假设您想要第二种行为。

在 .NET 中,“跳过调用堆栈”的唯一方法是抛出异常:

throw new Exception("...some message...");

但是,这将导致您的 VBA 应用程序执行其错误处理程序。如果您想返回特定的错误代码(以便您可以在 UI 层处理和/或忽略预期的异常),您可以使用特定的HResult 抛出异常,详情请参阅以下答案:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多