contact@consultdmw.com

How to Include Error Handling in VBA Code

For Microsoft® Access, Excel and Word, how to include error handling in Visual Basic for Applications (VBA) code to intercept and process errors when they occur.

Last updated on 2024-05-20.


Preface

A VBA procedure is a coded instruction to an application such as Excel to perform a task.

Errors occur during the execution of a VBA procedure due to a variety of reasons, including the use of incorrect code or the code attempting to run under circumstances for which it was not intended.

Introducing error handling (error trapping) in all your VBA procedures puts you in control of errors when they occur — puts you in the position to do something about them before they cause any harm.

By managing errors you can spare your users from being thrown into a panic at not knowing how to respond to a panic-inducing error messages, like this one;

Excel error message

Failure to include error handling may result in unwelcome and undesirable behaviour of the software — your users could be faced with corruption of their data.


Types of Procedures

Errors may occur during the execution of the two common VBA procedures, Sub Procedures and Function Procedures.

Sub Procedure A Sub Procedure performs a sequence of actions to complete a task, but does not return a result.

Say, you write a procedure to format your worksheet.

When you run it, the procedure adjusts fonts, colours and so on, but you don't intend it to return a value, as does any formula in your spreadsheet.

Function Procedure A Function Procedure will complete a sequence of actions and then return a result to the host applicaton. Think of the SUM function in Excel: it acts to add up the numbers in a collection of cells and returns the total to your spreadsheet.


Simple Sub Procedure Error Handler

There are a number of ways in which you might choose to include code for error handling in a macro. This is the skeleton code for a simple way:

Sub yourProcedureName()

On Error Goto errHandler


your code here


procDone:

Exit Sub

errHandler:

MsgBox Err.Number & ": " & Err.Description

Resume procDone

End Sub

The On Error statement turns on error trapping. Information about any error that occurs subsequent to this statement is stored in a VBA error object named Err.

In the event of an error, the On Error Goto errHandler statement instructs the procedure to stop executing your code at the point at which the error occurs, to skip to the errHandler label and to resume execution there.

MsgBox Err.Number & ": " & Err.Description sends a message box to the screen displaying information about the nature of the error:

Resume procDone instructs the procedure to resume executing at the procDone label.


Refined Error Handling Code

Let's assume you have wrapped a new procedure in the error-handling code described above. As you test your macro an error results. Therefore you are presented with the message box from which you learn the error number and the nature of the error.

Now you are in a position to revise your error handler to respond to this specific error (in this example the error number 1234):

Sub yourProcedureName()

On Error Goto errHandler


your code here


procDone:

Exit Sub

errHandler:

Select Case Err.Number

Case 1234

your code for handling error 1234

Case Else

' All outstanding errors

MsgBox Err.Number & ": " & Err.Description

End Select

Resume procDone

End Sub

As you test your macro and uncover other potential errors, you can extend the Select Case statement by including other Cases accordingly. In the following refinement of the macro, the messages to users are made specific:

Sub yourProcedureName()

On Error Goto errHandler

Dim msg$, title$, icon&


your code here


procDone:

Exit Sub

errHandler:

icon& = vbOKOnly + vbCritical

Select Case Err.Number

Case 53

title$ = "MISSING FILE"

msg$ = _

"Macro cannot locate an essential file." & _

vbNewline & vbNewLine & _

"Please notify IT support."

Case Else

title$ = "UNANTICIPATED ERROR"

msg$ = Err.Number & ": " & Err.Description & _

vbNewline & vbNewLine & _

"Please make a note of this message."

End Select

MsgBox msg$, icon&, title$

Resume procDone

End Sub

If when your procedure completes its run you want the user to be given a message about any error, then here is a further refinement of your code:

Sub yourProcedureName()

On Error Goto errHandler

Dim msg$, title$, icon&


your code here


title$="Macro Run Completed"

msg$ = "Please continue using the workbook"

icon& = vbOKOnly + vbInformation


procDone:

MsgBox msg$, icon&, title$

Exit Sub

errHandler:

icon& = vbOKOnly + vbCritical

Select Case Err.Number

Case 53

title$ = "MISSING FILE"

msg$ = "Macro cannot locate an essential file." & _

vbNewline & vbNewLine & _

"Please notify the developer."

Case Else

title$ = "UNANTICIPATED PROGRAM ERROR"

msg$ = _

Err.Number & ": " & Err.Description

vbNewline & vbNewLine & _

"Please make a note of this message."

End Select

Resume procDone

End Sub

For users who are adept at computer usage, as developer you will get targeted information about an error if you refine your error handler even further:

errHandler:

icon& = vbOKOnly + vbCritical

Select Case Err.Number

Case 53

title$ = "MISSING FILE"

msg$ = _

"Macro cannot locate an essential file." & _

vbNewline & vbNewLine & _

"Please notify the developer."

Case Else

title$ = "UNANTICIPATED PROGRAM ERROR"

msg$ = _

"Please take screen shot of this message." & _

vbNewLine & vbNewLine & _

"If not, make a note of these details:" & _

vbNewLine & vbNewLine & _

"Calling Proc: NameOfYourProcedure" & _

vbNewLine & _

"Error Number: " & Err.Number & _

vbNewLine & _

"Description: " & Err.Description & _

vbNewLine & vbNewLine & _

"Your closing message line … "

End Select

Resume procDone

The Case Else block responds to any error for which you have not specifically coded. So the bulk of the message it displays is information useful to you, the developer.

NameOfYourProcedure is the name you've given to the procedure in which you've included this error handler.

Program will now … is your message to the user about what will happen as a result of the error. You'll adapt this message as you deploy the error handler throughout your code modules.


Take Care—Test to Destruction

Always test your macros fully before putting them into service. Best to test on a back-up copy of your application.

“Pretty good testing is easy to do (that’s partly why some people like to say ‘testing is dead' — they think testing isn’t needed as a special focus because they note that anyone can find at least some bugs some of the time). Excellent testing is quite hard to do.”

James Bach (Satisfice, Inc.)

Testing takes time. To the time I estimate for writing the code, I add 30% at least for the testing.


Function Procedure Error Handlers

The error handler for a Function Procedure needs to be tailored to the nature of the result the function is meant to return to the host application.

The function may be designed to return a number, a date or some text, for example. So the result returned by its error handling needs to respond appropriately.


Your Support for DMW TIPS

Please support this website by making a donation to help keep it free of advertising and to help towards cost of time spent adding new content.

To make a contribution by PayPal in GBP (£ sterling) —

To make a contribution by PayPal in USD ($ US) —

Thanks, in anticipation.

“If debugging is the art of removing bugs, then programming must be the art of inserting them”

Author unknown