Can I terminate VBA macro execution with a C# dll

Viewed 66

In VBA I can terminate execution of macros using an End statement as follows.

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

I would like my C# DLL to contain a method that has the same effect? I am thinking of something along the following line.

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.
    }
}

I realize the End is a VBA statement, but I don't know how to reach VBA statements from within a C# DLL. (As this question demonstrates, I am new to C#.)

1 Answers

What does End in VBA do?

  • In the MS Access Runtime, it interrupts execution and closes the application.
  • In other Office applications (such as Excel, or Access in "non-runtime" mode) it interrupts execution and falls back through the call stack to the UI layer.

Since you tagged your question with "Excel", I assume that you want the second behavior.

In .NET, the only way to "jump through the call stack" is to throw an exception:

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

This, however, will cause your VBA application to execute its error handler. If you want to return a specific error code (so that you can handle and/or ignore expected exceptions at the UI layer), you can throw an exception with a specific HResult, see the following answer for details:

Related