Managing VBA Coding Errors

Error handling refers for error conditions that may arise when your program runs. Errors in general come in three ways:

Compile Time Error:  Such as undeclared variables that prevent your code from compiling and unknown keyword and punctuation omitted.

Logical Error: Occurs when you make a mistake in the logic that drives your script and you do not get the result you expected. You can’t catch these errors, because it depends on your requirement what type of logic you want to put in your code.

Run Time error: That occurs when VBA cannot correctly execute a program statement.

Typical run time errors include attempting to access a non-existent worksheet or workbook, or attempting to divide by zero etc.

On Error: This statement instructs VBA what to do when an run time error is occurred. The On Error statement takes three forms.

 On Error Goto 0:

is the default in VBA.  This indicates that when a run time error occurs VBA should display its default run time error box, allowing you to enter the code in debug mode or to terminate the VBA program.

On Error Resume Next: It instructs to VBA to ignore the error and resume execution on the next line in the sequence. It is very important to remember that On Error Resume Next does not in any way fix or solve the error. It simply instructs VBA to continue as if no error occurred.


On Error Goto <You’re Defined Label>: It tells VBA to transfer execution to the line following the specified line label. Whenever an error occurs, code execution immediately goes to the line following the line label.  None of the code between the error and the label is executed, including any loop control statements.

Example: Compile Time or Syntax Error

Sub Check_Error()

Dim name As String

name = “Rekha Mor”

MsgBox “Welcome ” & name ”

End Sub

Leave a Reply

Your email address will not be published.

Enjoy the tutorial? Please spread the word :)

Follow by Email