VBA:传递变量到错误处理
答
首先,我认为你的意思是:
on error goto label
不,你不能通过使用GOTO命令变量。但是,您可以检查细节Err.Description,如果你提出你自己的错误,你可以这样做:
' Raise a custom error.
Err.Raise Number:=vbObjectError + 1000, _
Source:="TestRaiseCustomError", _
Description:="My custom error description."
所以,如果你提出自己的错误,你可以设置源到战场。造成了这个问题。
请参阅使用错误对象的提升方法来提高自定义错误部分this link以获取更多信息。
答
您可以使用错误来得到错误号和说明
Sub|Function SomeName()
On Error GoTo Err_SomeName ' Initialize error handling.
' Code to do something here.
Exit_SomeName: ' Label to resume after error.
Exit Sub|Function ' Exit before error handler.
Err_SomeName: ' Label to jump to on error.
MsgBox Err.Number & Err.Description ' Place error handling here.
Resume Exit_SomeName ' Pick up again and quit.
End Sub|Function
答
我想不出一个聪明的办法做到这一点。我通常有一个错误handeling类/函数,我可以使用“错误goto”将错误传递给底部块,然后调用错误handeling函数。这样做的好处是有一个集中的错误处理程序是很好的,但也可以自定义它,所以在我的情况下,我传递了程序崩溃的名称。这并不漂亮,但如果你真的想要传递一组变量(取决于你有多少变量),或者设置一些东西来根据行号识别变量(你必须添加manuly ...) )
on error goto err
'Code
err:
ErrorHandeler err, "String with Procedure name"
答
声明全局变量并在代码和错误代码中使用它们。
Public global_variable1 As Integer
Public global_variable2 As String
Private Sub Btn1234_Click()
....
end sub
Err_abcd:
....
End Sub