Error Handling Techniques in VBA: Best Practices?

Error Handling Techniques in VBA: Best Practices?

rumyktndxpig
Observer Observer
1,596 Views
1 Reply
Message 1 of 2

Error Handling Techniques in VBA: Best Practices?

rumyktndxpig
Observer
Observer

Hi, My Name is Shami, and I work for Sandco Metal Industries  as a Stainless Steel Pipe Manufacturers in India  in the company. I'm relatively new to VBA and I've encountered some errors in my code. What are the recommended error-handling techniques in VBA to ensure smoother execution and better debugging? Are there specific methods or practices that seasoned VBA developers use to handle errors effectively?

 

 

@rumyktndxpig - this post has been edited due to Community Rules & Etiquette violation.

0 Likes
Accepted solutions (1)
1,597 Views
1 Reply
Reply (1)
Message 2 of 2

Ed__Jobe
Mentor
Mentor
Accepted solution

Hello @rumyktndxpig  There are two kinds of errors, compile errors and runtime errors. Compile errors are ones that have syntax problems that keep your code from compiling using the Compile command. Runtime errors occur when you run your code. These errors occur because of faulty logic. This is where error handling can help. Here you can trap for known errors and 'handle' them, but deciding what to do when one happens. You run the code and note the error number, then write code to handle that specific error. I also include a generic handler that displays the error number and message when you get an unexpected error.

Public Sub MyCommand()
    On Error GoTo Err_Control
    'This is where you write the main code of your command
    'Do some work here:

    'normal code execution exits the sub here
Exit_Here:
    Exit Sub
    'Beginning of error handler. Select..Case decides which error you have.
    'Below are some sample errors.
    'After handling each error, clear the Err object to be ready to handle the next error.
    'The Resume statement points to where you want to continue execution.
    'This can point to a Line Label anywhere in your code.
    'The last one, Case Else just prints out the error info for any unforseen error.
Err_Control:
    Select Case Err.Number
    Case Is = -2147352567
        'selection failed, user probably hit ESC. Just exit.
        Err.Clear
        Resume Exit_Here
    Case Is = -2145386493
        MsgBox Err.Number & ", " & "The proper block was not selected.", , "SyncSchedule"
        Err.Clear
        Resume Exit_Here
    Case Else
        MsgBox Err.Number & ", " & Err.Description, , "MyCommand"
        Err.Clear
        Resume Exit_Here
    End Select
End Sub

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes