Excel vba if value error

How to correct a #VALUE! error in the IF function IF is one of the most versatile and popular functions in Excel, and is often used multiple times in a single formula, as well as in combination with other functions. Unfortunately, because of the complexity with which IF statements can be built, it is […]

Содержание

  1. How to correct a #VALUE! error in the IF function
  2. Problem: The argument refers to error values
  3. Problem: The syntax is incorrect
  4. Need more help?
  5. Cell Error Values
  6. Пример
  7. Поддержка и обратная связь
  8. Cell Error Values
  9. Example
  10. Support and feedback
  11. VBA IFERROR
  12. IFERROR Function in VBA
  13. How to use IFERROR in VBA?
  14. Types of Errors, VBA IFERROR, Can Find
  15. Recommended Articles
  16. Cell Error Values
  17. Example
  18. Support and feedback

How to correct a #VALUE! error in the IF function

IF is one of the most versatile and popular functions in Excel, and is often used multiple times in a single formula, as well as in combination with other functions. Unfortunately, because of the complexity with which IF statements can be built, it is fairly easy to run into the #VALUE! error. You can usually suppress the error by adding error-handling specific functions like ISERROR, ISERR, or IFERROR to your formula.

Problem: The argument refers to error values

When there is a cell reference to an error value, IF displays the #VALUE! error.

Solution: You can use any of the error-handling formulas such as ISERROR, ISERR, or IFERROR along with IF. The following topics explain how to use IF, ISERROR and ISERR, or IFERROR in a formula when your argument refers to error values.

IFERROR was introduced in Excel 2007, and is far more preferable to ISERROR or ISERR, as it doesn’t require a formula to be constructed redundantly. ISERROR and ISERR force a formula to be calculated twice, first to see if it evaluates to an error, then again to return its result. IFERROR only calculates once.

=IFERROR(Formula,0) is much better than =IF(ISERROR(Formula,0,Formula))

Problem: The syntax is incorrect

If a function’s syntax is not constructed correctly, it can return the #VALUE! error.

Solution: Make sure you are constructing the syntax properly. Here’s an example of a well-constructed formula that nests an IF function inside another IF function to calculate deductions based on income level.

=IF(E2 IF(the value in cell A5 is less than 31,500, then multiply the value by 15%. But IF it’s not, check to see if the value is less than 72,500. IF it is, multiply by 25%, otherwise multiply by 28%).

To use IFERROR with an existing formula, you just wrap the completed formula with IFERROR:

=IFERROR(IF(E2 Note: The evaluation values in formulas don’t have commas. If you add them, the IF function will try to use them as arguments and Excel will yell at you. On the other hand, the percentage multipliers have the % symbol. This tells Excel you want those values to be seen as percentages. Otherwise, you would need to enter them as their actual percentage values, like “E2*0.25”.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Источник

Cell Error Values

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

Константа Номер ошибки Значение ошибки ячейки
xlErrDiv0 2007 #ДЕЛ/0!
xlErrNA 2042 #Н/Д
xlErrName 2029 #ИМЯ?
xlErrNull 2000 #NULL!
xlErrNum 2036 #ЧИСЛО!
xlErrRef 2023 #ССЫЛКА!
xlErrValue 2015 #ЗНАЧ!

Пример

В этом примере вставляется семь значений ошибки ячейки в ячейки A1:A7 на листе1.

В этом примере отображается сообщение, если активная ячейка на Листе1 содержит значение ошибки ячейки. Используйте этот пример в качестве основы для обработочного обработера ошибок со значением ячейки.

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

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

Источник

Cell Error Values

You can insert a cell error value into a cell or test the value of a cell for an error value by using the CVErr function. The cell error values can be one of the following xlCVError constants.

Constant Error number Cell error value
xlErrDiv0 2007 #DIV/0!
xlErrNA 2042 #N/A
xlErrName 2029 #NAME?
xlErrNull 2000 #NULL!
xlErrNum 2036 #NUM!
xlErrRef 2023 #REF!
xlErrValue 2015 #VALUE!

Example

This example inserts the seven cell error values into cells A1:A7 on Sheet1.

This example displays a message if the active cell on Sheet1 contains a cell error value. Use this example as a framework for a cell-error-value error handler.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA IFERROR

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 VBA On Error Resume Next VBA VBA 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 excel IFERROR Function In Excel The 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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA IFERROR (wallstreetmojo.com)

How to use IFERROR in VBA?

For example, take the above data only for a demonstration.

Step 1: Define the variable as an integer.

Code:

Step 2: To perform calculation, open For Next Loop.

Code:

Step 3: Inside, write the code as Cells(I,3).Value =

Code:

Step 4: To access the IFERROR function, we cannot simply type the formula; we need to use the “WorksheetFunction” class.

Code:

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:

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:

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

#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: –

Источник

Cell Error Values

You can insert a cell error value into a cell or test the value of a cell for an error value by using the CVErr function. The cell error values can be one of the following xlCVError constants.

Constant Error number Cell error value
xlErrDiv0 2007 #DIV/0!
xlErrNA 2042 #N/A
xlErrName 2029 #NAME?
xlErrNull 2000 #NULL!
xlErrNum 2036 #NUM!
xlErrRef 2023 #REF!
xlErrValue 2015 #VALUE!

Example

This example inserts the seven cell error values into cells A1:A7 on Sheet1.

This example displays a message if the active cell on Sheet1 contains a cell error value. Use this example as a framework for a cell-error-value error handler.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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

VBA IFERROR

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.

VBA IFERROR Example 2

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

VBA IFERROR Example 2-1

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

Example 2-2

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.

Example 2-3

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.

Example 2-4

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

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.

Точно так же, как мы используем ЕСЛИОШИБКА в Excel, чтобы знать, что делать, когда возникает ошибка перед каждой функцией, у нас есть встроенная функция ЕСЛИОШИБКА в VBA, которая используется таким же образом, поскольку это функция рабочего листа, мы используем эту функцию с worksheet.function метод в VBA, а затем мы предоставляем аргументы для функции.

Ожидать, что код будет работать без ошибок, — преступление. Для обработки ошибок в VBA у нас есть несколько способов использования таких операторов, как При ошибке Возобновить следующий VBAОператор VBA On Error Resume — это аспект обработки ошибок, используемый для игнорирования строки кода, из-за которой возникла ошибка, и продолжения со следующей строки сразу после строки кода с ошибкой.читать далее, При ошибке Возобновить Перейти к 0, При ошибке Перейти к метке. Обработчики ошибок VBA могут переходить только к следующей строке кода. Но в случае, если вычисление не происходит, нам нужно заменить ошибку на какое-то другое идентификационное слово. В этой статье мы увидим, как добиться этого с помощью VBA. ЕСЛИОШИБКА Функция в ExcelФункция ЕСЛИОШИБКА в Excel проверяет формулу (или ячейку) на наличие ошибок и возвращает указанное значение вместо ошибки.читать далее.

ЕСЛИ ОШИБКА VBA

Вы можете использовать это изображение на своем веб-сайте, в шаблонах и т. д. Пожалуйста, предоставьте нам ссылку на авторствоСсылка на статью должна быть гиперссылкой
Например:
Источник: VBA IFERROR (wallstreetmojo.com)

Как использовать ЕСЛИОШИБКА в VBA?

Здесь следует помнить, что это не Функция VBAФункции VBA служат основной цели для выполнения определенных вычислений и возврата значения. Поэтому в VBA мы используем синтаксис для указания параметров и типа данных при определении функции. Такие функции называются пользовательскими функциями.читать далее скорее просто как функция рабочего листа.

Вы можете скачать этот шаблон Excel VBA IFERROR здесь — Шаблон Excel для VBA ЕСЛИОШИБКА

Для примера возьмем приведенные выше данные только для демонстрации.

ЕСЛИ ОШИБКА VBA Пример 2

Шаг 1: Определите переменную как целое число.

Код:

Sub Iferror_Example1()

  Dim i As Integer

End Sub

Шаг 2: Для выполнения расчета откройте For Следующий цикл.

Код:

Sub Iferror_Example1()

  Dim i As Integer

  For i = 2 To 6

  Next i

End Sub

Шаг 3: Внутри напишите код как Ячейки(I,3).Значение =

Код:

Sub Iferror_Example1()

  Dim i As Integer

  For i = 2 To 6
     Cells(i,3).Value =
  Next i

End Sub

Шаг 4: Чтобы получить доступ к функции ЕСЛИОШИБКА, мы не можем просто ввести формулу; скорее, нам нужно использовать «Функция рабочего листа» класс.

Код:

Sub Iferror_Example1()

  Dim i As Integer

  For i = 2 To 6
    Cells(i, 3).Value = WorksheetFunction.If
  Next i

End Sub

ЕСЛИ ОШИБКА VBA Пример 2-1

Шаг 5: Как вы можете видеть на изображении выше, после вставки класса команды «WorksheetFunction» мы получаем формулу ЕСЛИОШИБКА. Выберите формулу.

Код:

Sub Iferror_Example1()

  Dim i As Integer

  For i = 2 To 6
    Cells(i, 3).Value = WorksheetFunction.IfError(
  Next i

End Sub

Пример 2-2

Шаг 6: Одна из проблем в VBA при доступе к функциям рабочего листа: мы не видим аргументы, подобные тому, что мы видели на рабочем листе. Вы должны быть уверены в аргументах, которые мы используем.

По этой причине, прежде чем я покажу вам IFERROR в VBA, я показал вам синтаксис функции рабочего листа.

Первый аргумент здесь — «Значение», т. е. какую ячейку вы хотите проверить? Перед этим примените расчет в Cell.

Пример 2-3

Теперь в VBA примените приведенные ниже коды.

Код:

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

Теперь функция ЕСЛИОШИБКА проверяет наличие ошибок в столбце C. Если обнаруживается какая-либо ошибка, в столбце D отображается результат «Не найдено».

Пример 2-4

Таким образом, используя функцию ЕСЛИОШИБКА, мы можем изменить результаты по своему желанию. В этом случае я изменил результат как «Не обнаружена.» Вы можете изменить это по своему требованию.

Типы ошибок, VBA IFERROR, можно найти

Важно знать виды Эксель ошибкиОшибки в Excel распространены и часто возникают во время применения формул. Список из девяти наиболее распространенных ошибок Excel: #DIV/0, #N/A, #NAME?, #NULL!, #NUM!, #REF!, #VALUE!, #####, Circular Reference.читать далее функция ЕСЛИОШИБКА может обработать. Ниже приведены типы ошибок, которые может обработать IFERROR.

#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME? или #NULL!.

УЗНАТЬ БОЛЬШЕ >>

Post Views: 828

VBA IFERROR

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.

Insert Module

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

VBA IFERROR Example 1-1

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

VBA IFERROR Example 1-2

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

VBA IFERROR Example 1-3

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

VBA IFERROR Example 1-4

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

VBA IFERROR Example 1-5

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

VBA IFERROR Example 1-6

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

VBA IFERROR Example 1-7

This completes the coding of VBA IFERROR. Now run the complete code by clicking on the play button as shown in below screenshot.

VBA IFERROR Example 1-8

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.

Example 2-1

For this open a new module in VBA and write Subcategory with the name of a performed function.

Code:

Sub VBA_IfError2()

End Sub

Example 2-2

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:

Example 2-3

Now select FormulaR1C1 from the list which is used for inserting any excel function.

Example 2-4

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

Example 2-5

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

Example 2-6

Now compile and run complete code using F5 key or manually and see the result as shown below.

Example 2-7

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–

  1. VBA Arrays
  2. VBA Number Format
  3. VBA Find
  4. VBA Do While Loop
 

se_arts

Пользователь

Сообщений: 20
Регистрация: 25.06.2016

#1

13.03.2018 10:34:11

Подскажите, пожалуйста, как правильно задается условие «если ошибка»
Мне необходимо указать ошибку: #ЗНАЧ!

Код
Sub test3()
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 4 To lastRow
        If Cells(i, 6).Value = 2 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 5
        If Cells(i, 6).Value = 5 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 10
'        If Cells(i, 6).Value = "#ЗНАЧ!" And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = Error And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = "#Error" And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = "#N/A" And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15      
    Next i
End Sub

Прикрепленные файлы

  • If_Error.xlsm (15.84 КБ)

 

Hugo

Пользователь

Сообщений: 23134
Регистрация: 22.12.2012

#2

13.03.2018 10:39:41

Код
If Cells(i, 6).Value = CVErr(xlErrNA)
 

se_arts

Пользователь

Сообщений: 20
Регистрация: 25.06.2016

#3

13.03.2018 11:48:34

Скрытый текст

Код
Sub test3()
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 4 To lastRow
        If Cells(i, 6).Value = 2 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 5
        If Cells(i, 6).Value = 5 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 10
        If Cells(i, 6).Value = CVErr(xlErrNA) And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
    Next i
End Sub

Выдает ошибку:
Run-time error ’13’:
Type mismatch

Изменено: se_arts13.03.2018 22:48:11

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

#4

13.03.2018 12:36:14

Код
If IsError(ActiveCell.Value) Then MsgBox "В ячейке - ошибка!"
 

Дмитрий Щербаков

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#5

13.03.2018 12:45:42

Цитата
se_arts написал:
If Cells(i, 6).Value = CVErr(xlErrNA) And Cells(i, 5).Value <> «» Then

В любом случае надо разбивать на два отдельных условия:

Код
If Cells(i, 5).Value <> "" Then
if Cells(i, 6).Value = CVErr(xlErrNA) then
Cells(i, 7).Value = 15
end if
end if

Но если надо проверять на ЛЮБЫЕ ошибки — то лучше воспользоваться вариантом ZVI

Цитата
ZVI написал:
If IsError(ActiveCell.Value) Then

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

se_arts

Пользователь

Сообщений: 20
Регистрация: 25.06.2016

#6

13.03.2018 14:24:57

Дмитрий, все равно выдает ошибку «13»

Код
Sub test3()
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 4 To LastRow
        If Cells(i, 6).Value = 2 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 5
        If Cells(i, 6).Value = 5 And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 10
'        If IsError(Cells(i, 6).Value) Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = CVErr(xlErrNA) And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = CVErr(xlErrValue) And Cells(i, 5).Value <> "" Then Cells(i, 7).Value = 15
'        If Cells(i, 6).Value = CVErr(xlErrValue) Then Cells(i, 7).Value = 15
'        If IsError(ActiveCell.Value) Then Cells(i, 7).Value = 15
'    If Cells(i, 5).Value <> "" Then
'    If Cells(i, 6).Value = CVErr(xlErrNA) Then
'    Cells(i, 7).Value = 15
'    End If
'    End If
    
    Next i
End Sub

Пробую разные варианты — выдает одну и туже ошибку «13» — может я синтаксис неверно пишу?
Не может быть, чтобы все предложенные варианты приводили к одной ошибке.
Что я не правильно делаю? Не читаете правила форума.
Рисунки удалены: превышение допустимого размера вложения
Кнопка для оформления кода в сообщении — <…>
[МОДЕРАТОР]

Изменено: se_arts13.03.2018 22:47:07

 

sokol92

Пользователь

Сообщений: 4429
Регистрация: 10.09.2017

У Вас ошибка выдается в строке (при i=16), следующей за заголовком цикла, которую Вы как раз не меняете во всех тестах. Смело нажимайте на Debug и убедитесь самостоятельно.

Изменено: sokol9213.03.2018 15:32:43

 

Hugo

Пользователь

Сообщений: 23134
Регистрация: 22.12.2012

#8

13.03.2018 22:43:51

Посмотрел наконец файл — точно xlErrValue нужно:

Код
Sub test2() 
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 4 To lastRow
        If Cells(i, 5).Value <> "" Then
            Select Case CStr(Cells(i, 6).Value)
            Case CStr(CVErr(xlErrValue)): Cells(i, 7).Value = 15
            Case "2": Cells(i, 7).Value = 5
            Case "5": Cells(i, 7).Value = 10
            End Select
            End If
        Next i
    End Sub

Или можно конечно искать просто «Error 2015»

Понравилась статья? Поделить с друзьями:
  • Excel stdole32 tlb error
  • Excel spill error
  • Excel runtime error 424 object required
  • Excel run time error 5 invalid procedure call or argument
  • Excel ref error