Is not error миф excel

Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.

Проверка переменных и выражений

Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.

Синтаксис функций для проверки переменных и выражений:

Expression — выражение, переменная или необязательный аргумент для IsMissing.

Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.

Функция IsArray

Описание функции

Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:

  • True — переменная является массивом;
  • False — переменная не является массивом.

Пример с IsArray

Sub Primer1()

Dim arr1(), arr2(1 To 10), arr3

    Debug.Print IsArray(arr1)  ‘Результат: True

    Debug.Print IsArray(arr2)  ‘Результат: True

    Debug.Print IsArray(arr3)  ‘Результат: False

arr3 = Array(1, 2, 3, 4, 5)

    Debug.Print IsArray(arr3)  ‘Результат: True

End Sub

Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.

Функция IsDate

Описание функции

Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:

  • True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
  • False — в иных случаях.

Пример с IsDate

Sub Primer2()

Dim d1 As String, d2 As Date

    Debug.Print IsDate(d1)  ‘Результат: False

    Debug.Print IsDate(d2)  ‘Результат: True

d1 = «14.01.2023»

    Debug.Print IsDate(d1)  ‘Результат: True

    Debug.Print IsDate(Now)  ‘Результат: True

End Sub

Функция IsEmpty

Описание функции

Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:

  • True — переменная содержит значение Empty;
  • False — переменной присвоено значение, отличное от Empty.

Пример с IsEmpty

Sub Primer3()

Dim s As String, v As Variant

    Debug.Print IsEmpty(s)  ‘Результат: False

    Debug.Print IsEmpty(v)  ‘Результат: True

v = 125

    Debug.Print IsEmpty(v)  ‘Результат: False

Range(«A1»).Clear

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: True

Range(«A1») = 123

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: False

End Sub

Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).

Функция IsError

Описание функции

Функция IsError возвращает логическое значение, указывающее, является ли аргумент функции значением ошибки, определенной пользователем:

  • True — аргумент функции является значением ошибки, определенной пользователем;
  • False — в иных случаях.

Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.

Пример с IsError

Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:

Function Vkuba(x)

    If IsNumeric(x) Then

        Vkuba = x ^ 3

    Else

        Vkuba = CVErr(25)

    End If

End Function

Sub Primer4()

    Debug.Print Vkuba(5)  ‘Результат: 125

    Debug.Print IsError(Vkuba(5))  ‘Результат: False

    Debug.Print Vkuba(«пять»)  ‘Результат: Error 25

    Debug.Print IsError(Vkuba(«пять»))  ‘Результат: True

End Sub

Функция IsMissing

Описание функции

Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:

  • True — если в процедуру не было передано значение для необязательного аргумента;
  • False — значение для необязательного аргумента было передано в процедуру.

Пример с IsMissing

Function Scepka(x, Optional y)

    If Not IsMissing(y) Then

        Scepka = x & y

    Else

        Scepka = x & » (а необязательный аргумент не подставлен)»

    End If

End Function

Sub Primer5()

    Debug.Print Scepka(«Тропинка», » в лесу»)  ‘Результат: Тропинка в лесу

    Debug.Print Scepka(«Тропинка»)  ‘Результат: Тропинка (а необязательный аргумент не подставлен)

End Sub

Функция IsNull

Описание функции

Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:

  • True — значением переменной или выражения является Null;
  • False — в иных случаях.

Пример с IsNull

Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:

Sub Primer6()

Dim Var

Var = Null

    If Var = Null Then Debug.Print Var  ‘Результат: «»

    If Var <> Null Then Debug.Print Var  ‘Результат: «»

    If IsNull(Var) Then Debug.Print Var  ‘Результат: Null

End Sub

Функция IsNumeric

Описание функции

Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:

  • True — если аргумент функции может рассматриваться как число;
  • False — в иных случаях.

Пример с IsNumeric

Sub Primer7()

Debug.Print IsNumeric(«3,14»)  ‘Результат: True

Debug.Print IsNumeric(«четыре»)  ‘Результат: False

End Sub

Функция IsObject

Описание функции

Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:

  • True — переменная содержит ссылку на объект или значение Nothing;
  • False — в иных случаях.

Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.

Пример с IsObject

Sub Primer8()

Dim myObj As Object, myVar As Variant

    Debug.Print IsObject(myObj)  ‘Результат: True

    Debug.Print IsObject(myVar)  ‘Результат: False

Set myVar = ActiveSheet

    Debug.Print IsObject(myVar)  ‘Результат: True

End Sub


Содержание

  1. Функция IsError
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. VBA ISERROR
  8. Excel VBA ISERROR Function
  9. Examples
  10. Example #1
  11. Example #2
  12. Things to Remember
  13. Recommended Articles
  14. VBA On Error – Error Handling Best Practices
  15. VBA Errors Cheat Sheet
  16. Errors
  17. VBA Error Handling
  18. VBA On Error Statement
  19. On Error GoTo 0
  20. On Error Resume Next
  21. VBA Coding Made Easy
  22. Err.Number, Err.Clear, and Catching Errors
  23. Error Handling with Err.Number
  24. On Error GoTo Line
  25. On Error Exit Sub
  26. Err.Clear, On Error GoTo -1, and Resetting Err.Number
  27. VBA On Error MsgBox
  28. VBA IsError
  29. If Error VBA
  30. VBA Error Types
  31. Runtime Errors
  32. Syntax Errors
  33. Compile Errors
  34. Debug > Compile
  35. OverFlow Error
  36. Other VBA Error Terms
  37. VBA Catch Error
  38. VBA Ignore Error
  39. VBA Throw Error / Err.Raise
  40. VBA Error Trapping
  41. VBA Error Message
  42. VBA Error Handling in a Loop
  43. VBA Error Handling in Access
  44. VBA Code Examples Add-in

Функция IsError

Возвращает значение типа Boolean, указывающее, является ли аргумент expression значением ошибки.

Синтаксис

IsError(expression)

Обязательным аргументомвыражения может быть любое допустимое выражение.

Замечания

Значения ошибок создаются путем преобразования реальных чисел в значения ошибок с помощью функции CVErr . Функция IsError используется для определения того, представляет ли числовое выражение ошибку. Функция IsError возвращает значение True, если аргумент expression обозначает ошибку; в противном случае она возвращает значение False.

Пример

В этом примере функция IsError используется для проверки того, является ли числовое значение кодом ошибки. Функция CVErr используется для возврата варианта ошибки из функции, определенной пользователем. Предположим, что UserFunction это определяемая пользователем процедура функции, которая возвращает значение ошибки. Например, возвращаемое значение, присвоенное инструкцией UserFunction = CVErr(32767) , где 32767 является определяемым пользователем числом.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA ISERROR

Excel VBA ISERROR Function

VBA IsError, the function name itself, sums up the functionality. This function will identify whether or not the value we have supplied is an error value. If the supplied or range reference value is an error value, we will get the result as “TRUE.” If the value is not an error, we will get the result as “FALSE.”

Table of contents

Syntax

The expression is nothing but the value we are testing or the cell reference value or formula expression. And as you can see, the result will be “Boolean.”

Examples

Example #1

We will see a simple example to find whether the value is an error. For example, we have the below value in cell A1.

We will test whether this value is an error value or not.

Code:

  • Declare a variable to store the cell A1 value.

Code:

  • Now, assign the value of cell A1 to this variable in VBA.

Code:

  • Now, test whether this variable value is an error or not.

Code:

  • Enclose this result in a message box in VBA.

Code:

Let us run the code and see the result of the ISERROR function.

The result is TRUE because the value in cell A1 is #DIV/0! which is the division error.

Now, we will change the value of cell A1 to “Hello.”

Now run the code and see the result.

So, the result is FALSE now because the value in cell A1 is not the error value.

So, first, we need to understand the error types and why they occur in the Excel worksheet. Below are the detailed error values and explanations.

  • #DIV/0: This error occurs when we try to divide the number by zero. This error is called “Division by Zero.”
  • #N/A: When you try to fetch the data from different tables, and if it finds no value, then we will get this error, which is called “Not Available.”
  • #NAME?: If Excel cannot recognize the formula or name, we will get this error.
  • #NULL!: When you specify space between the cell referencesCell ReferencesCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more instead of a comma.
  • #NUM!: The numerical value supplied to the data isn’t a valid one.
  • #VALUE!: When you reference the cell values for mathematical calculations, and if the number format is not correct, we will get this error.
  • #REF!: If the cell is a formula, it has cell references. If that referenced cell deletes, then we will get this reference error.

Example #2

Now, look at the below data set.

We need to identify the error values from this list and store the result, either TRUE or FALSE, in the next column.

Since we need to test more than one cell, we need to include this in loops. The below code will identify the error values.

Code:

When you run this code, we will get the below result in column 4.

Wherever TRUE is, that value is an error value.

Things to Remember

  • The ISERROR function returns the Boolean type result, i.e., TRUE or FALSE.
  • It is available as a worksheet function as well as a VBA functionVBA 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 .
  • It is useful as part of large VBA projects.
  • It recognizes only pre-determined error values (Read error type).

Recommended Articles

This article has been a guide to VBA ISERROR. Here, we discuss how the Excel VBA ISERROR function identifies whether the value we have supplied is an error value or not with examples. You can learn more about VBA functions from the following articles: –

Источник

VBA On Error – Error Handling Best Practices

In this Article

VBA Errors Cheat Sheet

Errors

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:

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):

On Error Resume Next

On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.

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.

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!

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’.

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.

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):

and create a line label like this:

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 do this by placing the error handler line label at the end of your procedure:

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:

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:

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.

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:

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.

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.

VBA Ignore Error

To ignore errors in VBA, simply use the On Error Resume Next statement:

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:

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:

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.

VBA Error Handling in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Is it possible to use something with similar functionality as Iferror(value, value_if_error) or Iserror(value) in VBA?

I tried to write:

If IsError(Cells(i, c) / curr) Then
'CODE BLOCK 1
else
'CODE BLOCK 2
end if

But VBA tells me that I have division by zero error when it tries to run the if-statement. It throws me into debug. But this is just the type of thing I want to trigger CODE BLOCK 1!

Community's user avatar

asked Sep 1, 2013 at 19:48

user1283776's user avatar

user1283776user1283776

18.8k43 gold badges135 silver badges267 bronze badges

7

The usual way to handle this would be

i = 0
On Error Resume Next
n = 1 / i
If Err.Number <> 0 Then
    'Handle error - code block 1
    Err.Clear
    On Error GoTo 0
Else
    On Error GoTo 0
    ' No error - code block 2

End If

answered Sep 2, 2013 at 6:37

chris neilsen's user avatar

chris neilsenchris neilsen

52.2k10 gold badges84 silver badges122 bronze badges

You can call all worksheet functions using Application.WorksheetFunction.IsError(args)

You could also try doing the calculation in a cell directly and query it’s value. For example, very hacky:

Sub asdf()

    Dim ws As New Worksheet
    Set ws = ActiveSheet

    Dim i As Double
    i = 0
    ws.Range("A2").Formula = "=iserror(A1 / " & i & ")"

    If ws.Range("A2").Value Then
        Debug.Print "Error caught"
    Else
        Debug.Print "No error"
    End If

End Subu

GreenGiant's user avatar

GreenGiant

4,8381 gold badge47 silver badges75 bronze badges

answered Sep 1, 2013 at 19:54

JustinJDavies's user avatar

JustinJDaviesJustinJDavies

2,6434 gold badges30 silver badges52 bronze badges

2

Errors Happen

We may come across several functions in programming languages. In VBA, we are prone to encounter errors like: 

  1. Syntax errors
  2. Compile time errors
  3. 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: 

  1. <source value> is the cell from which text is copied
  2. <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

Example of a program to past one column's cell values into another

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

An example showing the difference between the simple paste and paste data using “iferror” function in VBA.

The image above shows the difference between the simple paste and paste data using the “IfError” function in VBA.

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.

Example of choosing a list and setting the range as the source.

The items are now listed here:

Example of where the items selected are listed.

Now I apply the vlookup formula to get the price/piece of the selected item.

Applying the vlookup formula to get the price of a 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.

Selecting an item from the list in cell H4 that does have 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.

Using the “IfError” formula which can filter such errors and display a value which 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.

Example of proper value being 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:

Example 1 of using a macro code in VBA.

Example 2 of using a macro code in VBA.

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.

Example 1 of output values for corresponding input values.

Example 2 of output values for corresponding input values.

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

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.

iferror function excel

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:

iferror function 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)

excel iferror then 0

If Error Then Blank

Instead of setting errors to 0, you can set them to ‘blank’ with double quotations (“”):

=IFERROR(A2/B2,"")

iferror then blank

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")

iferror vlookup zero

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)))

iferror nested vlookup multiple sheets

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 vlookup

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 index match

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)}

iferror array formula

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))}

iferror array function excel

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")

ifna function excel

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)

if iserror formula excel

IFERROR in Google Sheets

The IFERROR Function works exactly the same in Google Sheets as in Excel:

iferror function google sheets

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):

vba iferror example

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)"

vba code generator

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.

Like this post? Please share to your friends:
  • Is not a swear word
  • Is northeast one word
  • Is non stop one word
  • Is noisily a word
  • Is noisiest a word