VBA - 出错时转到 ErrHandler:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23687970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:09:47  来源:igfitidea点击:

VBA - On Error GoTo ErrHandler:

vbaerror-handling

提问by user3283415

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

我有一个关于 VBA 中错误处理的简单问题。我知道如何使用该On Error GoTo ErrHandler语句,但在指定的标签上使用我自己的代码,我宁愿使用预制的 VBA 消息。在 C# 中是这样的:

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

采纳答案by Andy G

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

在您的错误处理程序代码中,您可以访问Err.NumberErr.Description。在没有错误处理的情况下您会看到错误消息中的描述,因此与ex.Message您的代码示例中的描述相同。

回答by RubberDuck

Create an ErrorHandler Module and place this sub in it.

创建一个 ErrorHandler 模块并将此子程序放入其中。

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.

我使用模块作用域常量来保存模块名称。修改以满足您的需求。