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
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
This tutorial demonstrates how to use the Excel IFERROR Function to catch formula errors, replacing them with another formula, blank value, 0, or a custom message.
What Is the IFERROR Function?
IFERROR allows you to perform a calculation. If the calculation does not result in an error, then the calculation result is displayed. If the calculation does result in an error then another calculation is performed (or a static value like 0, blank, or some text is outputted).
When would you use the IFERROR Function?
- When dividing numbers to avoid errors caused by dividing by 0
- When performing lookups to prevent errors if the value isn’t found.
- When you want to perform another calculation if the first results in an error (ex. Lookup a value in a 2nd table if it’s not found in the first table)
Un-handled formula errors can cause errors within your workbook, but visible errors also make your spreadsheet less visibly appealing.
If Error Then 0
Let’s look at a basic example. Below you are dividing two numbers. If you attempt to divide by zero you will receive an error:
Instead, insert the calculation within the IFERROR Function and if you divide by zero a 0 is outputted instead of an error:
=IFERROR(A2/B2,0)
If Error Then Blank
Instead of setting errors to 0, you can set them to ‘blank’ with double quotations (“”):
=IFERROR(A2/B2,"")
We will look at more IFERROR usages with the VLOOKUP Function…
IFERROR with VLOOKUP
Lookup functions like VLOOKUP will generate errors if the lookup value is not found. As shown above, you can use the IFERROR Function to replace errors with blanks (“”) or 0s:
=IFERROR(VLOOKUP(A2,LookupTable1!$A$2:$B$4,2,FALSE),"not found")
If Error Then Do Something Else
The IFERROR Function can also be used to perform a 2nd calculation if the 1st calculation results in an error:
=IFERROR(VLOOKUP(A2,LookupTable1!$A$2:$B$4,2,FALSE),
VLOOKUP(A2,LookupTable2!$A$2:$B$4,2,FALSE))
Here if the data is not found in ‘LookupTable1’ a VLOOKUP is performed on ‘LookupTable2’ instead.
More IFERROR Formula Examples
Nested IFERROR – VLOOKUP Multiple Sheets
You can nest an IFERROR inside another IFERROR to perform 3 separate calculations. Here we will use two IFERRORs to perform VLOOKUPs on 3 separate worksheets:
=IFERROR(VLOOKUP(A2,LookupTable1!$A$2:$B$4,2,FALSE),
IFERROR(VLOOKUP(A2,LookupTable2!$A$2:$B$4,2,FALSE),
VLOOKUP(A2,LookupTable3!$A$2:$B$4,2,FALSE)))
Index / Match & XLOOKUP
Of course, IFERROR will also work with Index / Match and XLOOKUP formulas as well.
IFERROR XLOOKUP
The XLOOKUP Function is an advanced version of the VLOOKUP function.
=IFERROR(XLOOKUP(A2,LookupTable1!$A$2:$A$4,LookupTable1!$B$2:$B$4),"Not Found")
IFERROR INDEX / MATCH
INDEX and MATCH can be used to create more powerful VLOOKUPs (similar to how the new XLOOKUP function works) in Excel.
=IFERROR(INDEX(LookupTable1!$B$2:$B$4,MATCH(A3,LookupTable1!$A$2:$A$4,0)),"Not Found")
IFERROR in Arrays
Array formulas in Excel are used to perform several calculations through a single formula. Let’s suppose there are three columns of Year, Sales, and Avg Price. You can find out the total quantity with the following formula in the E column.
{=SUM($B$2:$B$4/$C$2:$C$4)}
The formula performs well until it attempts to divde by zero, resulting in the #DIV/0! error.
You can use the IFERROR function like this to resolve the error:
{=SUM(IFERROR($B$2:$B$4/$C$2:$C$4,0))}
Notice that the IFERROR function must be nested inside the SUM Function, otherwise the IFERROR will apply to the sum total and not each individual item in the array.
IFNA vs. IFERROR
The IFNA Function works exactly the same as the IFERROR Function except the IFNA function will only catch #N/A errors. This is extremely useful when working with lookup functions: regular formula errors will still be detected, but no error will appear if the lookup value is not found.
=IFNA(VLOOKUP(A2,LookupTable1!$A$2:$B$4,2,FALSE),"Not Found")
If ISERROR
If you are still using Microsoft Excel 2003 or an older version, then you can substitute IFERROR with a combination of IF and ISERROR. Here is a brief example:
=IF(ISERROR(A2/B2),0,A2/B2)
IFERROR in Google Sheets
The IFERROR Function works exactly the same in Google Sheets as in Excel:
IFERROR Examples in VBA
VBA does not have a built-in IFERROR Fucntion, but you can also access the Excel IFERROR Function from within VBA:
Dim n as long
n = Application.WorksheetFunction.IfError(Value, value_if_error)
Application.WorksheetFunction gives you access to many (not all) Excel functions in VBA.
Typically IFERROR is used when reading values from cells. If a cell contains an error, VBA may throw an error message when attempting to process the cell value. Try this out with the example code below (where cell B2 contains an error):
Sub IFERROR_VBA()
Dim n As Long, m As Long
'IFERROR
n = Application.WorksheetFunction.IfError(Range("b2").Value, 0)
'No IFERROR
m = Range("b2").Value
End Sub
The code assigns cell B2 to a variable. The second variable assignment throws an error because the cell value is #N/A, but the first works fine because of the IFERROR function.
You can also use VBA to create a formula containing the IFERROR Function:
Range("C2").FormulaR1C1 = "=IFERROR(RC[-2]/RC[-1],0)"
Error handling in VBA is much different than in Excel. Typically, to handle errors in VBA, you will use VBA Error Handling. VBA Error Handling looks like this:
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
Notice we use If Err.Number <> 0 Then to identify if an error has occurred. This is a typical way to catch errors in VBA. However, the IFERROR Function has some uses when interacting with Excel cells.
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
You can use the following basic syntax to use the IFERROR function in VBA to display a specific value in a cell if an error is encountered in an Excel formula:
Sub IfError()
Dim i As Integer
For i = 2 To 11
Cells(i, 4).Value = WorksheetFunction.IfError(Cells(i, 3).Value, "Formula Error")
Next i
End Sub
This particular example checks if each cell in rows 2 through 11 of the third column in the current sheet has an error value.
If an error value is encountered, a value of “Formula Error” is assigned to the corresponding cell in the fourth column, otherwise the numerical value from the third column is assigned to the corresponding value in the fourth column.
The following example shows how to use this syntax in practice.
Suppose we have the following dataset in Excel that shows the total revenue and units sold of some product at different stores:
Column C uses a formula to divide Revenue by Units Sold to come up with Revenue per Unit.
However, notice that the formula produces a value of #DIV/0! in some cells where we attempt to divide by zero.
Suppose we would like to create a new column that instead displays “Formula Error” for those cells.
We can create the following macro to do so:
Sub IfError()
Dim i As Integer
For i = 2 To 11
Cells(i, 4).Value = WorksheetFunction.IfError(Cells(i, 3).Value, "Formula Error")
Next i
End Sub
When we run this macro, we receive the following output:
The values in column D either show the results from the formula in column C or they display a value of “Formula Error” if an error value is shown.
Feel free to change “Formula Error” in the IfError method in the code to instead display whatever value you would like when an error is encountered.
Note: You can find the complete documentation for the VBA IfError method here.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Use IF OR to Test Multiple Conditions
VBA: How to Use IF AND to Test Multiple Conditions
VBA: How to Use IF NOT to Test if Condition is Not Met