​A selection of topics on IT and its application to finance. 
​Send me your comments, questions ​or suggestions by clicking
h​ere


elmama
A simple error handling technique for VB/VBA code

You should include error handling in all your VB or VBA code. Here's a simple but
effective way to do so.

​Private Sub CommandButton_Click()
On Error GoTo err_handler
'All your main code goes below
'
...
...
​' Now the error handling bit
endit:
Exit Sub

err_handler:
MsgBox _
"An unexpected error has been detected" & Chr(13) & _
"Description is: " & Err.Number & ", " & Err.Description & Chr(13) & _
"Module is: commandbutton_click" & Chr(13) & _
"Please note the above details before contacting support"
Resume endit
​End Sub

​One of the good things about doing it this way is that the error handling code is
the same for every module with the exception of the Module is: part of the
msgbox statement. It's simply a matter of cutting and pasting the code to your
other modules. Easy and effective.