Excel VBA If NA: How to Handle #N/A Errors in Macros
In this article
To handle an #N/A error in Excel VBA, you cannot use a standard "If cell.Value = "#N/A"" statement because #N/A is an error value, not a string, and comparing it directly will cause the code to crash with a Type Mismatch error. Instead, you must use the IsError() function to detect the error first, or use Application.VLookup instead of Application.WorksheetFunction.VLookup to allow the error to be returned as a variant rather than triggering a runtime exception.
What You'll Need
- Microsoft Excel installed on Windows or macOS.
- The Developer tab enabled in the Excel Ribbon (Right-click any tab > Customize the Ribbon > Check "Developer").
- A dataset containing potential #N/A values, typically resulting from VLOOKUP, MATCH, or INDEX functions.
- Basic familiarity with opening the Visual Basic Editor (ALT + F11).
Step-by-Step
- Open the Visual Basic Editor: Press
ALT + F11on your keyboard to open the VBA window. Go toInsert > Moduleto create a new space for your code. - Declare Your Variables: When dealing with potential #N/A errors, you must declare your result variable as a
Variant. This is critical because aStringorDoublevariable cannot hold an error value; attempting to assign #N/A to a non-variant variable will cause an immediate "Type Mismatch" error. - Choose Your Lookup Method: There are two primary ways to call Excel functions in VBA. If you use
WorksheetFunction.VLookup, VBA will throw a runtime error the moment a value is not found. If you useApplication.VLookup, VBA returns the error value to the variable without crashing, allowing you to handle it with anIfstatement. - Implement the IsError Check: Use the
IsError()function to verify if the result is an error before attempting to use the value. For example:Dim result As Variant result = Application.VLookup("SearchTerm", Range("A1:B10"), 2, False) If IsError(result) Then MsgBox "Value not found!" Else MsgBox "Value found: " & result End If - Handle Specific #N/A Logic: While
IsError()catches all errors (like #REF! or #VALUE!), you can specifically target #N/A by checking the error number. UseCVErr(xlErrNA)to ensure you are only reacting to "Not Available" results and not other critical spreadsheet failures. - Loop Through a Range: If you are checking a column of existing formulas for #N/A values, iterate through the cells using a
For Eachloop. Inside the loop, apply theIsError()check to the.Valueproperty of each cell. If the cell contains #N/A, you can then use.Value = ""or.Value = 0to clean the data. - Test the Code: Run your macro using the
F5key. Test it with a value that exists in your table and a value that definitely does not exist to ensure both theIfandElseblocks execute correctly.
Common Mistakes
The most frequent mistake is attempting to compare a cell value directly to a string, such as If Range("A1").Value = "#N/A" Then. In Excel, #N/A is a special error type, not text. When VBA encounters an error value during a direct comparison, it stops execution and displays a "Run-time error 13: Type Mismatch." Always use IsError() before checking the content of a cell that might contain a formula error.
Another common error is using WorksheetFunction.VLookup without an On Error Resume Next statement. While Application.VLookup returns an error value that can be handled by an If statement, WorksheetFunction triggers a hard VBA exception. If you prefer the WorksheetFunction syntax, you must wrap it in an error handler, or your macro will crash every time a lookup fails.
Many users also forget to declare their variables as Variant. If you declare Dim result As String and the lookup returns #N/A, the code will fail at the assignment line, long before it ever reaches your If IsError() check. The Variant type is the only data type capable of holding the Error subtype generated by Excel functions.
Tips
For cleaner code, create a custom wrapper function. Instead of writing the IsError logic every time you perform a lookup, write a function called SafeVLookup that returns a default value (like an empty string or a zero) whenever an #N/A is encountered. This keeps your main business logic uncluttered.
If you are processing thousands of rows, avoid checking IsError inside a loop that interacts with the worksheet directly. Instead, load the entire range into a VBA Array. Processing the errors within an array in memory is significantly faster than reading each cell individually from the sheet, which reduces the overhead of the Excel COM interface.
Consider using Application.Match if you only need to know if a value exists and don't actually need to retrieve data from another column. Match is more efficient than VLookup and returns the same error types, making it compatible with the IsError() and CVErr(xlErrNA) logic described above.
Troubleshooting
If your code is still crashing with a "Type Mismatch" error despite using IsError(), check the line where the value is assigned to the variable. Ensure the variable is declared as Variant. If you are using WorksheetFunction.VLookup, switch to Application.VLookup; the latter is designed to return the error to the variable rather than crashing the script.
If IsError() returns True but you believe the cell is not an error, check for hidden characters or formatting. Sometimes cells look like they contain #N/A but are actually text strings that say "#N/A". In this rare case, IsError() will return False. You can verify this by using TypeName(Range("A1").Value); a real error will return "Error", while a string will return "String".
If your macro is skipping cells or not identifying errors correctly, ensure that your loop is correctly referencing the cell's value. Use If IsError(cell.Value) Then rather than If IsError(cell) Then. Referencing the cell object itself instead of its value can lead to unpredictable results depending on the version of Excel you are using.
Frequently Asked Questions
What is the difference between Application.VLookup and WorksheetFunction.VLookup?
Application.VLookup returns a Variant containing the error value if the lookup fails, allowing you to handle it with an If statement. WorksheetFunction.VLookup triggers a runtime exception that requires On Error handling to prevent the macro from stopping.
Can I use IIf() to handle #N/A errors?
No, IIf() evaluates both the True and False parts regardless of the condition. If the False part involves a calculation with an #N/A value, it will trigger a Type Mismatch error even if the condition was True. Use a standard If...Then...Else block instead.
How do I clear all #N/A errors in a column using VBA?
The fastest way is to use the SpecialCells method. Use Range("A:A").SpecialCells(xlCellTypeFormulas, xlErrors).ClearContents. This targets only cells with formulas that result in errors, bypassing the need for a loop.
Does IsError() catch all types of Excel errors?
Yes, IsError() returns True for any Excel error, including #N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, and #NAME?. To isolate specifically #N/A, compare the result to CVErr(xlErrNA).
Why does my code work in the worksheet but fail in VBA?
Excel worksheets have built-in error handling (like the IFERROR function) that suppresses crashes. VBA is a strict programming language; any operation performed on an error value that isn't explicitly handled as a Variant will cause the program to terminate.