VBA - On Error GoTo ErrHandler:

2020-04-27 09:25发布

I have a simple question about error-handling in VBA. I know how to use the On Error GoTo ErrHandler statement but instead using my own code at the specified label, I would rather use a prefabricated VBA-message. Something like this in C#:

catch(Exception ex){
    Console.Writeline(ex.Message);
}

2条回答
闹够了就滚
2楼-- · 2020-04-27 09:59

In your error handler code your can access the Err.Number and Err.Description. The Description in the error message you would have seen without error handling, so is the equivalent of ex.Message in your code sample.

查看更多
够拽才男人
3楼-- · 2020-04-27 10:05

Create an ErrorHandler Module and place this sub in it.

Public Sub messageBox(moduleName As String, procName As String, Optional style As VbMsgBoxStyle = vbCritical)
    MsgBox "Module: " & moduleName & vbCrLf & _
        "Procedure: " & procName & vbCrLf & _
        Err.Description, _
        style, _
        "Runtime Error: " & Err.number
End Sub

Call it from anywhere in your project like so.

Private sub Foo()
On Error GoTo ErrHandler

'do stuff

ExitSub:
    ' clean up before exiting
    Exit Sub
ErrHandler:
    ErrorHandler.messageBox "ThisModuleName","Foo"
    Resume ExitSub
End Sub

I use a module scoped constant to hold the module name. Modify to suit your needs.

查看更多
登录 后发表回答