简体   繁体   中英

Inconsistent VBA Error Message Box?

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. :-)

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. :-)

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.

在类模块中声明sub为friend而不是public

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM