Just like we use IFERROR in Excel to know what to do when we encounter an error before every function, we have an inbuilt IFERROR function in VBA used in the same fashion. Since it is a worksheet function, we use this function with the worksheet.function method in VBA, and then we provide the arguments for the function.
IFERROR Function in VBA
It is a crime to expect the code to function without throwing any error. To handle errors in VBA, we have several ways using statements like On Error Resume Next VBAVBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error.read more, On Error Resume Goto 0, On Error GoTo Label. VBA error handlers can only proceed further to the next line of code. But if the calculation does not happen, we need to replace the error with another identity word. In this article, we will see how to achieve this by using the VBA IFERROR Function in excelThe IFERROR function in Excel checks a formula (or a cell) for errors and returns a specified value in place of the error.read more.
Table of contents
- IFERROR Function in VBA
- How to use IFERROR in VBA?
- Types of Errors, VBA IFERROR, Can Find
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IFERROR (wallstreetmojo.com)
How to use IFERROR in VBA?
The thing to remember here is it is not a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more but rather just a worksheet function.
You can download this VBA IFERROR Excel Template here – VBA IFERROR Excel Template
For example, take the above data only for a demonstration.
Step 1: Define the variable as an integer.
Code:
Sub Iferror_Example1() Dim i As Integer End Sub
Step 2: To perform calculation, open For Next Loop.
Code:
Sub Iferror_Example1() Dim i As Integer For i = 2 To 6 Next i End Sub
Step 3: Inside, write the code as Cells(I,3).Value =
Code:
Sub Iferror_Example1() Dim i As Integer For i = 2 To 6 Cells(i,3).Value = Next i End Sub
Step 4: To access the IFERROR function, we cannot simply type the formula; we need to use the “WorksheetFunction” class.
Code:
Sub Iferror_Example1() Dim i As Integer For i = 2 To 6 Cells(i, 3).Value = WorksheetFunction.If Next i End Sub
Step 5: As you can see in the above image, after inserting the command “WorksheetFunction” class, we get the IFERROR formula. Select the formula.
Code:
Sub Iferror_Example1() Dim i As Integer For i = 2 To 6 Cells(i, 3).Value = WorksheetFunction.IfError( Next i End Sub
Step 6: One of the problems in VBA is that while accessing the worksheet functions, we do not get to see the arguments we have seen in the worksheet. It would help if you were sure about the arguments we are using.
It is the reason before we show you the IFERROR in VBA, We have shown you the syntax of the worksheet function.
The first argument is “Value,” i.e., what cell do you want to check? Before this, apply the calculation in the cell.
Now, in the VBA, apply the codes below.
Code:
Sub Iferror_Example1() Dim i As Integer For i = 2 To 6 Cells(i, 4).Value = WorksheetFunction.IfError(Cells(i, 3).Value, "Not Found") Next i End Sub
Now, the IFERROR function checks for any error in column C. If it finds any error, it will show the result as “Not Found” in column D.
Using the IFERROR function, we can alter the results per our wish. In this case, we have altered the result as “Not Found.” We can change this to your requirement.
Types of Errors, VBA IFERROR, Can Find
Knowing the types of excel errorsErrors in excel are common and often occur at times of applying formulas. The list of nine most common excel errors are — #DIV/0, #N/A, #NAME?, #NULL!, #NUM!, #REF!, #VALUE!, #####, Circular Reference.read more the IFERROR function can handle is important. Below are the kind of errors IFERROR can handle.
#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!.
Recommended Articles
This article is a guide to VBA IFERROR Function. Here, we learned how to use the VBA IFERROR function in Excel, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –
- VBA Type Statement
- VBA Type Mismatch Error
- What is OR Function in VBA?
- Excel VLOOKUP Errors
Errors Happen
We may come across several functions in programming languages. In VBA, we are prone to encounter errors like:
- Syntax errors
- Compile time errors
- Runtime errors
These are errors in code which can be handled using error handling methods. For example, you can see some best practices in articles like this one.
In this article, we will discuss some logical errors which will give unexpected output.
Example Scenario
Let us try to copy the contents of a cell to another while the data in the cell has invalid or improper data like a “DIV/0” error which we are not aware of.
In this case, the contents would simply get pasted as-is. But we do not want to use this erroneous data in another sheet or any cell in the same sheet.
In that case, we need an option wherein the copy paste happens only if the source data is error-free. In case of error, we need some specific statement to be pasted there.
The IfError function of VBA can help us achieve this easily.
IfError Function
The IfError function can help point out/display obvious errors in other functions that may not catch our eye easily.
This function is used to prevent mathematical errors or any other errors that occur from a copy paste action when the source value or the resulting value has an error. This function displays resulting values only if they are error-free. If there are errors in the output values, an alternate statement text is displayed.
Syntax:
IfError( < source value> , <alternate text> )
Where:
<source value>
is the cell from which text is copied<alternate text>
is the statement to be used in case the value of source text is erroneous.
Paste One Column’s Cell Values to Another With and Without the IfError Function
Sub ifferror_demo() 'just a for loop to iterate through each row starting from 1 to 20 For i = 1 To 20 ' simply paste the cell values of col 4 to col 6 Cells(i, 6).Value = Cells(i, 4).Value &<pre&>&<code&>' paste the values of col 4 to col 6 only if the values have no errors. If not "invalid numbers" will be pasted. Cells(i, 5).Value = WorksheetFunction.IfError(Cells(i, 4).Value, "Invalid numbers")&>/code&>&</pre&>; Next End Sub
The data in column E pasted using the IfError function looks reasonable and clear.
But the data in col F that has been pasted without using the “IfError” function has not corrected/checked anything for us.
Program That Uses IfError With Vlookup
In this program, we will try to see the price/piece of any item that is selected from a list in a cell.
Price/piece is in col D and the item is in col A. So, we will use “vlookup” here.
I’m setting data validation to list the items in cell H4.
For this, we can go to Data tab-> Data tools-> Data validation.
Choose a list and select the range as the source.
The items are now listed here:
Now I apply the vlookup formula to get the price/piece of the selected item.
Now I select some item from the list in cell H4 that has a “Division by 0 error” in col D, eg: Cake.
To avoid this kind of output, we have to use the “IfError” formula, which can filter out these errors and display a value that the viewers can understand.
Here, the existing vlookup formula is wrapped in an “IfError” formula with the vlookup formula as the first argument. The second argument is an alternate text to be displayed in case the result is erroneous.
The proper value would be displayed in case the output is error-free.
Do the same using a macro code (VBA):
Sub Excel_IFERROR_demo() ' declare a variable of type worksheet Dim ws As Worksheet ' assign the worksheet Set ws = Worksheets("Snackbar") ' apply the Excel IFERROR function with the vlookup function ws.Range("I4") = Application.WorksheetFunction.IfError(Application.VLookup(ws.Range("H4").Value, ws.Range("A1:D13"), 4, False), "CHECK THE VALUE") End Sub
Now, we will delete the formula in cell “I4” and use this macro to fill the data in that cell.
What does this code do?
This declares a worksheet object, assigns the worksheet to it. Then, we assign the vlookup formula to the cell I4 . The formula depends on the value in cell H4.
Whenever we change the value in cell H4, this code should be run to fill the corresponding value in cell I4.
A couple of output results to demonstrate how this code works:
A Program for Mathematical Calculation
This program is for direct division or calculation of price/piece for the item “Roti.”
Sub Excel_IFERROR_demo_2() ' declare a variable of type worksheet Dim ws As Worksheet ' assign the worksheet Set ws = Worksheets("Snackbar") ' apply the Excel IFERROR function with the vlookup function ws.Range("D7") = Application.WorksheetFunction.IfError(ws.Range("B7").Value / ws.Range("C7").Value, "CHECK THE VALUE") End Sub
Here the formula =B7/C6
in the cell D7 is replaced by the output of this code.
A couple of output values for corresponding input values.
Note: Change the values of B7 or C7 or both and run this procedure (code) to see the output in D7.
Summary
“IfError” is available both as a formula and VBA function in Microsoft Excel. This helps us catch the logical faults (e.g.: Math calculations) and not the syntax or compile errors. They are mostly used in Excel formulae directly instead of macros. In the case of automated macro utilities that are large in size, they can be used in the respective VBA code too.
Tagged with: Error, error handling, Errors, Excel, Functions, IfError, Macro, macro code, VBA, VBA For Excel, worksheet functions
VBA IFERROR
A written code many times gives the error and chances of getting an error in complex error are quite high. Like excel has IFERROR function which is used where there are chances of getting an error. IFERROR changes the error message into other text statements as required and defined by the user. Similarly, VBA IFERROR functions same as the IFERROR function of Excel. It changes the error message into the defined text by the user.
This error mostly occurs when we perform any mathematical function or if we are mapping any data which is in a different format. IFERROR handles many errors, some of them are:
#VALUE!, #N/A, #DIV/0!, #REF!, #NUM!, #NULL! And #NAME?
Example #1
Now this IFERROR function can also be implemented in VBA. Now to compare the results from Excel with VBA IFERROR we will insert a column where we will apply VBA IFERROR statement as shown below.
You can download this VBA IFERROR Excel Template here – VBA IFERROR Excel Template
For this, we consider the same data and insert another column where we will perform VBA IFERROR. Go to VBA window and insert a new Module from Insert menu as shown below.
Now in a newly opened module, write Sub-category with any name. Here we have given the name of the operating function as shown below.
Code:
Sub VBA_IfError() End Sub
Now with the help of ActiveCell, we will select the first reference cell and then directly use IFERROR Formula with reference cell (RC) -2 divided by -1 cell numbers. Which means we are dividing cell A by cell B in the first argument. And in the second argument write any statement which we want in place of error. Here we will use the same state which we have seen above i.e. “No Product Class”.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" End Sub
Now select the range cell which would be our denominator. Here we have selected cell C2.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" Range("C2").Select End Sub
Now to drag the formula to below cells where we need to apply IFERROR till the table has the values.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" Range("C2").Select Selection.End(xlDown).Select End Sub
Now to come to the last cell of the column with the help of command Range where we need to drag the IFERROR formula. Here our limit ends at cell D6.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" Range("C2").Select Selection.End(xlDown).Select Range("D6").Select End Sub
Now to drag the applied IFERROR down to all the applicable cells select the Range from End (or Last) cell to Up to the applied formula cell by End(xlUp) command under Range.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" Range("C2").Select Selection.End(xlDown).Select Range("D6").Select Range(Selection, Selection.End(xlUp)).Select End Sub
As we do Ctrl + D to drag the up cell values to all selected cells in excel, here in VBA, Selection.FillDown is used to fill the same up cells values in all selected cells.
Code:
Sub VBA_IfError() ActiveCell.FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],""No Product Class"")" Range("C2").Select Selection.End(xlDown).Select Range("D6").Select Range(Selection, Selection.End(xlUp)).Select Selection.FillDown End Sub
This completes the coding of VBA IFERROR. Now run the complete code by clicking on the play button as shown in below screenshot.
As we can see above, in column D starting from Cell 2 to 6 we got our results.
There is another format and way to apply IFERROR in VBA. For this, we will consider another set of data as shown below. Below we have sales data of some products in column A and quality sold in column B. And we need map this data at cell F2 with reference to product type Laptop. Now data in the first table has #N/A in cell B3 with for Laptop quantity sold out which means that source data itself has an error. And if we look up the data from the first table to Cell F2 we will get same #N/A here.
For this open a new module in VBA and write Subcategory with the name of a performed function.
Code:
Sub VBA_IfError2() End Sub
Select range where we need to see the output or directly activate that cell by ActiveCell followed by dot (.) command line as shown below.
Code:
Now select FormulaR1C1 from the list which is used for inserting any excel function.
Now use the same formula as used in excel function in VBA as well.
Code:
Sub VBA_IfError2() ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],R[-1]C[-5]:R[3]C[-4],2,0),""Error In Data"")" End Sub
Now select the cell where we need to see the output in Range. Here we have selected cell F3.
Code:
Sub VBA_IfError2() ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],R[-1]C[-5]:R[3]C[-4],2,0),""Error In Data"")" Range("B8").Select End Sub
Now compile and run complete code using F5 key or manually and see the result as shown below.
As we can see in the above screenshot, the output of product type Laptop, from first table #N/A is with error text “Error In Data” as defined in VBA code.
Pros of VBA IFERROR Function
- It takes little time to apply the IFERROR function through VBA.
- Result from Excel insert function and VBA IFERROR coding, both are the same.
- We can format or paste special the applied formula as well to avoid any further problem.
Cons of VBA IFERROR Function
- IFERROR with this method, referencing the range of selected cell may get disturbed as the table has limited cells.
Things To Remember
- We can record the macro and modify the recorded coding as per our need.
- Always remember to save the file as Macro-Enabled Excel, so that we can use the applied or created macro multiple times without any issue.
- Make sure you remember to compile the complete code before ending the command function. By this, we can avoid or correct any error incurred.
- You can apply the created code into a button or tab and use it by a single click. This is the quickest way to run the code.
- Best way to avoid any changes after running the code is to paste special the complete cells so that there will not be any formula into the cell.
Recommended Articles
This has been a guide to Excel VBA IFERROR Function. Here we discussed how to use IFERROR Function in VBA along with some practical examples and downloadable excel template. You can also go through our other suggested articles–
- VBA Arrays
- VBA Number Format
- VBA Find
- VBA Do While Loop
What is the declared type of SumIfInt
? If that’s Integer
, its maximum legal value is 32,767, because Integer
is a 16-bit type — and using a 16-bit signed integer type to represent row numbers in an Excel worksheet is a good way to achieve run-time error 6 «Overflow».
Use a 32-bit integer type instead:
Dim SumIfInt As Long
If Sheets("Bridge").Range("D" & SumIfInt)
is a very small value, it’s possible that using it as a denominator makes the result overflow an Integer
, or possibly even a Long
— in that case you should probably use a Double
floating-point type instead.
When it hits an error, I want it to return a 0.
Better code wouldn’t hit an error at all. The only error you should be worried about here, is «Division by Zero» — actually also «Type Mismatch» if any of the involved cells may contain an error value — in any case, shoving the error under the carpet with On Error Resume Next
isn’t showing you anything about how to avoid that situation in the future.
The best error-handling code is code that avoids raising avoidable errors in the first place.
Dim divisorValue As Variant
divisorValue = Sheets("Bridge").Range("D" & SumIfInt)
If IsError(divisorValue) Or IsEmpty(divisorValue) Then
' return 0 and bail out
Exit Function
End If
Dim divisor As Double
divisor = CDbl(divisorValue)
Now use the known-to-be-ok divisor
value instead.
A note about your object management: you’re dereferencing the exact same object reference multiple times — that’s inefficient.
If Sheets("Bridge")
exists at compile-time in ThisWorkbook
(the workbook that’s running the code), then you never need to dereference it that way — VBA creates a global-scope object variable for every single worksheet in the workbook — select it in the VBE’s Project Explorer (Ctrl+R), bring up its Properties (F4), then set its (Name)
to something meaningful, e.g. BridgeSheet
. Then you can do this:
BridgeSheet.Range("D" & SumIfInt)
Another tip: the more you cram into a single instruction, the harder debugging becomes, because the more possible failing points there are.
Consider pulling the invidividual values involved into their own variables, then validating them, then performing the division once you know doing that isn’t going to blow up.
In this Article
- VBA Errors Cheat Sheet
- Errors
- VBA Error Handling
- VBA On Error Statement
- On Error GoTo 0
- On Error Resume Next
- Err.Number, Err.Clear, and Catching Errors
- On Error GoTo Line
- VBA IsError
- If Error VBA
- VBA Error Types
- Runtime Errors
- Syntax Errors
- Compile Errors
- Debug > Compile
- OverFlow Error
- Other VBA Error Terms
- VBA Catch Error
- VBA Ignore Error
- VBA Throw Error / Err.Raise
- VBA Error Trapping
- VBA Error Message
- VBA Error Handling in a Loop
- VBA Error Handling in Access
VBA Errors Cheat Sheet
Errors
On Error – Stop code and display error
On Error Goto 0
On Error – Skip error and continue running
On Error Resume Next
On Error – Go to a line of code [Label]
On Error Goto [Label]
Clears (Resets) Error
On Error GoTo –1
Show Error number
MsgBox Err.Number
Show Description of error
MsgBox Err.Description
Function to generate own error
Err.Raise
See more VBA “Cheat Sheets” and free PDF Downloads
VBA Error Handling
VBA Error Handling refers to the process of anticipating, detecting, and resolving VBA Runtime Errors. The VBA Error Handling process occurs when writing code, before any errors actually occur.
VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:
- Referencing a non-existent workbook, worksheet, or other object (Run-time Error 1004)
- Invalid data ex. referencing an Excel cell containing an error (Type Mismatch – Run-time Error 13)
- Attempting to divide by zero
VBA On Error Statement
Most VBA error handling is done with the On Error Statement. The On Error statement tells VBA what to do if it encounters an error. There are three On Error Statements:
- On Error GoTo 0
- On Error Resume Next
- On Error GoTo Line
On Error GoTo 0
On Error GoTo 0 is VBA’s default setting. You can restore this default setting by adding the following line of code:
On Error GoTo 0
When an error occurs with On Error GoTo 0, VBA will stop executing code and display its standard error message box.
Often you will add an On Error GoTo 0 after adding On Error Resume Next error handling (next section):
Sub ErrorGoTo0()
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0
'Run More Code
End Sub
On Error Resume Next
On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.
On Error Resume Next
Note: On Error Resume Next does not fix an error, or otherwise resolve it. It simply tells VBA to proceed as if the line of code containing the error did not exist. Improper use of On Error Resume Next can result in unintended consequences.
A great time to use On Error Resume Next is when working with objects that may or may not exist. For example, you want to write some code that will delete a shape, but if you run the code when the shape is already deleted, VBA will throw an error. Instead you can use On Error Resume Next to tell VBA to delete the shape if it exists.
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0
Notice we added On Error GoTo 0 after the line of code containing the potential error. This resets the error handling.
In the next section we’ll show you how to test if an error occurred using Err.Number, giving you more advanced error handling options.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Err.Number, Err.Clear, and Catching Errors
Instead of simply skipping over a line containing an error, we can catch the error by using On Error Resume Next and Err.Number.
Err.Number returns an error number corresponding with the type of error detected. If there is no error, Err.Number = 0.
For example, this procedure will return “11” because the error that occurs is Run-time error ’11’.
Sub ErrorNumber_ex()
On Error Resume Next
ActiveCell.Value = 2 / 0
MsgBox Err.Number
End Sub
Error Handling with Err.Number
The true power of Err.Number lies in the ability to detect if an error occurred (Err.Number <> 0). In the example below, we’ve created a function that will test if a sheet exists by using Err.Number.
Sub TestWS()
MsgBox DoesWSExist("test")
End Sub
Function DoesWSExist(wsName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Sheets(wsName)
'If Error WS Does not exist
If Err.Number <> 0 Then
DoesWSExist = False
Else
DoesWSExist = True
End If
On Error GoTo -1
End Function
Note: We’ve added a On Error GoTo -1 to the end which resets Err.Number to 0 (see two sections down).
With On Error Resume Next and Err.Number, you can replicate the “Try” & “Catch” functionality of other programming languages.
On Error GoTo Line
On Error GoTo Line tells VBA to “go to” a labeled line of code when an error is encountered. You declare the Go To statement like this (where errHandler is the line label to go to):
On Error GoTo errHandler
and create a line label like this:
errHandler:
Note: This is the same label that you’d use with a regular VBA GoTo Statement.
Below we will demonstrate using On Error GoTo Line to Exit a procedure.
On Error Exit Sub
You can use On Error GoTo Line to exit a sub when an error occurs.
You can do this by placing the error handler line label at the end of your procedure:
Sub ErrGoToEnd()
On Error GoTo endProc
'Some Code
endProc:
End Sub
or by using the Exit Sub command:
Sub ErrGoToEnd()
On Error GoTo endProc
'Some Code
GoTo skipExit
endProc:
Exit Sub
skipExit:
'Some More Code
End Sub
Err.Clear, On Error GoTo -1, and Resetting Err.Number
After an error is handled, you should generally clear the error to prevent future issues with error handling.
After an error occurs, both Err.Clear and On Error GoTo -1 can be used to reset Err.Number to 0. But there is one very important difference: Err.Clear does not reset the actual error itself, it only resets the Err.Number.
What does that mean? Using Err.Clear, you will not be able to change the error handling setting. To see the difference, test out this code and replace On Error GoTo -1 with Err.Clear:
Sub ErrExamples()
On Error GoTo errHandler:
'"Application-defined" error
Error (13)
Exit Sub
errHandler:
' Clear Error
On Error GoTo -1
On Error GoTo errHandler2:
'"Type mismatch" error
Error (1034)
Exit Sub
errHandler2:
Debug.Print Err.Description
End Sub
Typically, I recommend always using On Error GoTo -1, unless you have a good reason to use Err.Clear instead.
VBA On Error MsgBox
You might also want to display a Message Box on error. This example will display different message boxes depending on where the error occurs:
Sub ErrorMessageEx()
Dim errMsg As String
On Error GoTo errHandler
'Stage 1
errMsg = "An error occured during the Copy & Paste stage."
'Err.Raise (11)
'Stage 2
errMsg = "An error occured during the Data Validation stage."
'Err.Raise (11)
'Stage 3
errMsg = "An error occured during the P&L-Building and Copy-Over stage."
Err.Raise (11)
'Stage 4
errMsg = "An error occured while attempting to log the Import on the Setup Page"
'Err.Raise (11)
GoTo endProc
errHandler:
MsgBox errMsg
endProc:
End Sub
Here you would replace Err.Raise(11) with your actual code.
VBA IsError
Another way to handle errors is to test for them with the VBA ISERROR Function. The ISERROR Function tests an expression for errors, returning TRUE or FALSE if an error occurs.
Sub IsErrorEx()
MsgBox IsError(Range("a7").Value)
End Sub
VBA Programming | Code Generator does work for you!
If Error VBA
You can also handle errors in VBA with the Excel IFERROR Function. The IFERROR Function must be accessed by using the WorksheetFunction Class:
Sub IfErrorEx()
Dim n As Long
n = WorksheetFunction.IfError(Range("a10").Value, 0)
MsgBox n
End Sub
This will output the value of Range A10, if the value is an error, it will output 0 instead.
VBA Error Types
Runtime Errors
As stated above:
VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:
- Referencing a non-existent workbook, worksheet, or other object
- Invalid data ex. referencing an Excel cell containing an error
- Attempting to divide by zero
You can “error handle” runtime errors using the methods discussed above.
Syntax Errors
VBA Syntax Errors are errors with code writing. Examples of syntax errors include:
- Mispelling
- Missing or incorrect punctuation
The VBA Editor identifies many syntax errors with red highlighting:
The VBA Editor also has an option to “Auto Syntax Check”:
When this is checked, the VBA Editor will generate a message box alerting you syntax errors after you enter a line of code:
I personally find this extremely annoying and disable the feature.
Compile Errors
Before attempting to run a procedure, VBA will “compile” the procedure. Compiling transforms the program from source code (that you can see) into executable form (you can’t see).
VBA Compile Errors are errors that prevent the code from compiling.
A good example of a compile error is a missing variable declaration:
Other examples include:
- For without Next
- Select without End Select
- If without End If
- Calling a procedure that does not exist
Syntax Errors (previous section) are a subset of Compile Errors.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Debug > Compile
Compile errors will appear when you attempt to run a Procedure. But ideally, you would identify compile errors prior to attempting to run the procedure.
You can do this by compiling the project ahead of time. To do so, go to Debug > Compile VBA Project.
The compiler will “go to” the first error. Once you fix that error, compile the project again. Repeat until all errors are fixed.
You can tell that all errors are fixed because Compile VBA Project will be grayed out:
OverFlow Error
The VBA OverFlow Error occurs when you attempt to put a value into a variable that is too large. For example, Integer Variables can only contain values between -32,768 to 32,768. If you enter a larger value, you’ll receive an Overflow error:
Instead, you should use the Long Variable to store the larger number.
Other VBA Error Terms
VBA Catch Error
Unlike other programming languages, In VBA there is no Catch Statement. However, you can replicate a Catch Statement by using On Error Resume Next and If Err.Number <> 0 Then. This is covered above in Error Handling with Err.Number.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA Ignore Error
To ignore errors in VBA, simply use the On Error Resume Next statement:
On Error Resume Next
However, as mentioned above, you should be careful using this statement as it doesn’t fix an error, it just simply ignores the line of code containing the error.
VBA Throw Error / Err.Raise
To through an error in VBA, you use the Err.Raise method.
This line of code will raise Run-time error ’13’: Type mismatch:
Err.Raise (13)
VBA Error Trapping
VBA Error Trapping is just another term for VBA Error Handling.
VBA Error Message
A VBA Error Message looks like this:
When you click ‘Debug’, you’ll see the line of code that is throwing the error:
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA Error Handling in a Loop
The best way to error handle within a Loop is by using On Error Resume Next along with Err.Number to detect if an error has occurred (Remember to use Err.Clear to clear the error after each occurrence).
The example below will divide two numbers (Column A by Column B) and output the result into Column C. If there’s an error, the result will be 0.
Sub test()
Dim cell As Range
On Error Resume Next
For Each cell In Range("a1:a10")
'Set Cell Value
cell.Offset(0, 2).Value = cell.Value / cell.Offset(0, 1).Value
'If Cell.Value is Error then Default to 0
If Err.Number <> 0 Then
cell.Offset(0, 2).Value = 0
Err.Clear
End If
Next
End Sub
VBA Error Handling in Access
All of the above examples work exactly the same in Access VBA as in Excel VBA.
Function DelRecord(frm As Form)
'this function is used to delete a record in a table from a form
On Error GoTo ending
With frm
If .NewRecord Then
.Undo
Exit Function
End If
End With
With frm.RecordsetClone
.Bookmark = frm.Bookmark
.Delete
frm.Requery
End With
Exit Function
ending:
End
End Function