vba: passing a variable into error handles

后端 未结 4 1636
后悔当初
后悔当初 2021-01-25 13:22

i have a statement:

on error go to label

however i would like to pass into the label the variable which caused the error

is this possib

相关标签:
4条回答
  • 2021-01-25 13:44

    Declare global variables and use them in the code and in your error code.

    Public global_variable1 As Integer
    Public global_variable2 As String
    
    Private Sub Btn1234_Click()
    ....
    end sub
    
    Err_abcd:                           
    ....
    End Sub
    
    0 讨论(0)
  • 2021-01-25 13:45

    You can use Err to get the error No and Description

     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
    
    0 讨论(0)
  • 2021-01-25 13:47

    I can't think of a clever way to do it. I normally have an error handeling class/function that way I can use "on error goto" to pass the error to the bottom block then call the error handeling function. The advantage of this is it's nice to have a centralised error handler but also you can customise it so in my case I pass the name of the procedure thats crashed. It's not pretty but you could if you really wanted to pass either a collection of variables (dependant on how many you have) or set up something to identify the variable based on the line number (which you'd have to add manauly...)

    on error goto err
    
    'Code
    
    err:
    
    ErrorHandeler err, "String with Procedure name"
    
    0 讨论(0)
  • 2021-01-25 13:49

    First, I think you mean:

    on error goto label
    

    And no, you can't pass variables using a goto command. However, you can check the Err.Description for details, and if you are raising your own errors, you can do this:

      ' Raise a custom error.
        Err.Raise Number:=vbObjectError + 1000, _
            Source:="TestRaiseCustomError", _
            Description:="My custom error description."
    

    So if you are raising your own error, you could set Source to the field that caused the problem.

    Refer to the Use the Err Object's Raise Method to Raise Custom Errors section at this link for more info.

    0 讨论(0)
提交回复
热议问题