Home » excel » excel vba – Inconsistent VBA Error Message Box?

excel vba – Inconsistent VBA Error Message Box?

Posted by: admin March 9, 2020 Leave a comment

Questions:

It seems that the message box that VBA pops-up when an unhandled exception occurs behaves differently depending on… something? To see what I mean, create a new .xlsm, then create a standard module Module1; paste inside this code then paste inside Sheet1 Worksheet object this code:

Public Sub TestErrMsgBox()
    Debug.Print "Hello!"
    Call Err.Raise(Number:=vbObjectError, Source:="VBAProject.Sheet1",  Description:="Lorem Ipsum")
End Sub

On my Excel 2010 Professional Plus, calling the subroutine in the VBE’s “Immediate” (Ctrl+G) window:


Call Module1.TestErrMsgBox

Call Sheet1.TestErrMsgBox

will show the error message Automation Error / Invalid OLEVERB structure.

Now, if one calls directly the Raise method from in the “Immediate” window:

Call Err.Raise(Number:=vbObjectError, Source:="VBAProject.Sheet1",  Description:="Lorem Ipsum")

it will show the (expected) error message Lorem Ipsum.

What exactly changes in the error handling, or in the Err object, from the first case to the last? and how it may be manipulated? I figured out that in the first case the message depends only on the Number argument in Raise call, but still it doesn’t explain…

I find this a bit annoying, because I expected my messages displayed, not something else. There’s always available the Pokemon approach (catching all the exceptions and showing custom MessageBoxes based on Err properties), but I’d like to understand what happens. 🙂

Later edit:

The behavior described above happens when “Error Trapping” is set on “Break on Unhandled Errors.” Once I put “Break on All Errors” it displays the correct message, with the “Debug” button available; however, this is not a good idea, to break execution on every error…

Also, thanks to the feedback from Alex K., roryap and Doug Glancy I figured out that this happens when the TestErrMsgBox subroutine is called from within a Worksheet object, not from a standard Module as I incorrectly reported the first time. The posting is fixed; however, the question is still there. 🙂

How to&Answers:

The reason it happens when your Sub is in a Sheet module and you’ve set the VBE to Break on Unhandled Errors, has to do with the fact that a Sheet module is a class module. Set Error Trapping to Break in Class Modules, and it will behave correctly.

I always use this setting anyways, so I can debug inside UserForms and classes.

Searching “VBA err.raise invalid oleverb structure break in class module” seems to support the fact that it’s related to class modules.

Answer:

Declare sub as friend in class module instead of public