Excel VBA If Object Is Not Nothing: Guide and Examples
In this article
To check if an object has been successfully assigned in Excel VBA, use the syntax If Not objectVariable Is Nothing Then. This specific logic is required because objects in VBA are pointers to memory addresses; you cannot use a simple equals sign (=) to check for existence. Using this check prevents the dreaded "Object variable or With block variable not set" runtime error (Error 91), which occurs when you attempt to call a property or method on an object that does not actually exist in memory.
What You'll Need
- Microsoft Excel installed on Windows or macOS.
- The Developer tab enabled in the Excel Ribbon.
- Basic familiarity with opening the Visual Basic Editor (ALT + F11).
- An understanding of the difference between standard variables (like Integer or String) and Object variables (like Range, Worksheet, or Workbook).
Step-by-Step
- Open the Visual Basic Editor: Press
ALT + F11on your keyboard to launch the VBA environment. - Insert a New Module: Go to the
Insertmenu and selectModule. This creates a clean space to write your procedure. - Declare Your Object Variable: At the top of your sub-procedure, declare the object you intend to use. For example, if you are searching for a specific cell, use
Dim myRange As Range. It is critical to use theDimstatement so VBA knows this variable is an object and not a simple value. - Attempt to Assign the Object: Use a method that might fail. A common example is the
Findmethod. Write:Set myRange = Range("A1:A10").Find(What:="TargetValue"). Note the use of theSetkeyword; failing to useSetwhen assigning objects will cause a compile error. - Implement the "Not Nothing" Check: Immediately after the assignment attempt, wrap your subsequent logic in an
If Not ... Is Nothingblock.If Not myRange Is Nothing Then MsgBox "Object found! The value is at " & myRange.Address Else MsgBox "Object not found." End If - Execute the Code: Press
F5or click the Run button. If the search term exists in the range, the first block executes. If it does not, theElseblock handles the failure gracefully instead of crashing the program.
Common Mistakes
The most frequent error developers make is using the equals operator (=) instead of the Is operator. In VBA, = is used for comparing values (like 5 = 5), while Is is used to compare object references. Writing If myRange = Nothing Then will trigger a "Object does not support this operator" error because you are asking VBA to compare the contents of the object rather than checking if the pointer exists.
Another common mistake is forgetting the Not keyword. If you write If myRange Is Nothing Then, the code inside the block will only run if the object was not found. While this is syntactically correct, beginners often mix up the logic, leading to code that executes the "failure" logic when the object is actually present.
Finally, omitting the Set keyword during assignment is a recurring issue. For standard variables like Dim x As Integer, you simply write x = 10. However, for objects, myRange = Range("A1") will fail. You must use Set myRange = Range("A1"). Without Set, VBA tries to assign the default property of the object to the variable, which usually results in a type mismatch error.
Tips
To keep your code clean, especially in large projects, consider creating a helper function that returns a Boolean value based on whether an object exists. This prevents your main logic from being cluttered with nested If Not ... Is Nothing blocks.
When working with multiple objects, always perform the Is Nothing check as early as possible. This is known as a "Guard Clause." Instead of wrapping your entire script in a giant If block, check if the object is nothing and Exit Sub immediately if it is. This reduces the indentation level of your code and makes it significantly more readable.
Combine this check with On Error Resume Next when dealing with objects that might throw an error before they even return a Nothing value. For example, when referencing a worksheet that might not exist, you can suppress the error, attempt the Set command, and then use If Not ... Is Nothing to determine if the assignment actually worked. Just remember to set On Error GoTo 0 immediately after the check to re-enable standard error reporting.
Troubleshooting
If your code is still throwing "Error 91: Object variable or With block variable not set" despite having a check in place, verify that you aren't calling a property of the object before the If Not ... Is Nothing line. Even a simple Debug.Print myRange.Value placed above the check will crash the macro if the object is null.
If the code always goes to the Else block (meaning the object is always Nothing) even when you believe the object should exist, check your assignment logic. If you are using .Find, ensure that the LookIn and LookAt parameters are explicitly defined. The Find method remembers the settings from the last time the user performed a manual search in the Excel UI; if the last manual search was set to "Match entire cell contents" and your VBA search is looking for a partial string, it will return Nothing.
If you encounter a "Type Mismatch" error, double-check your Dim statements. Ensure the variable is declared as a generic Object or a specific class (like Worksheet). If you declare a variable as a String but try to Set it to a Range object, the Is Nothing check will never be reached because the code will crash during the assignment phase.
Frequently Asked Questions
Why can't I just use If myRange = Nothing?
In VBA, objects are references to locations in memory. The = operator compares values, but the Is operator compares the memory addresses. Since Nothing represents the absence of a reference, you must use Is to check if the variable points to any valid object.
What is the difference between Nothing and an empty string?
Nothing is a state for object variables only, meaning the variable is not linked to any instance of a class. An empty string ("") is a value assigned to a string variable. You cannot check if a string Is Nothing; you must check if it = "".
Do I need to set an object to Nothing when I am finished?
While VBA has automatic garbage collection that cleans up objects when a procedure ends, explicitly setting an object to Nothing (e.g., Set myRange = Nothing) is a good practice in very large loops or complex applications to free up memory immediately.
Can I use this check for a Worksheet that doesn't exist?
Yes, but only if you use On Error Resume Next first. Attempting to Set ws = Sheets("MissingSheet") will trigger a runtime error before the If Not ... Is Nothing check can even run. By suppressing the error, the variable remains Nothing, allowing your check to work.
Does this work for arrays?
No. Arrays are not objects in the same sense. To check if a dynamic array has been initialized, you cannot use Is Nothing. Instead, you typically use a custom function involving the UBound function wrapped in an error handler to see if the array contains any elements.