c# - 我可以用 C# dll 终止 VBA 宏执行吗

标签 c# excel vba

在 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# 的新手。)

最佳答案

End 在 VBA 中有什么作用?

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

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

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

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

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

关于c# - 我可以用 C# dll 终止 VBA 宏执行吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62504304/

相关文章:

C# 枚举或 int 常量

c# - 将数组添加到 web.config 中的键

c# - TextBox 中的水印/提示/占位符文本?

Excel VBA 复制粘贴到单元格中不会触发 worksheet_change

excel - Excel 2003 中的 PtrSafe 给我带来了问题

c# - 这真的是节省分配吗?

c# - 微软办公自动化 : Get notified (Event) when a macro runs

excel - OleDb - 从 Excel 读取缓慢

excel - VBA 编译器不允许在方法参数周围使用括号

vba - 如何以编程方式添加 Excel 2010 宏