Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA If Not Is Nothing: Usage and Examples

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To check if an object variable has been successfully assigned in Excel VBA, use the syntax If Not myObject Is Nothing Then. This specific logical construction is required because object variables (like Ranges, Worksheets, or Charts) do not hold simple values; they hold references to memory addresses. When an object is first declared or fails to be found during a search, it is set to Nothing. The Not operator reverses the logic, allowing the code to execute only when the object actually exists and is ready for use.

What You'll Need

  • Microsoft Excel installed on Windows or macOS.
  • Access to the Visual Basic Editor (VBE), typically opened by pressing Alt + F11.
  • A basic understanding of how to insert a Module into a VBA project.
  • An existing workbook with some data to test search and assignment functions.

Step-by-Step

  1. Open the Visual Basic Editor: Launch Excel and press Alt + F11. In the top menu, go to Insert > Module to create a new space for your code.
  2. Declare Your Object Variable: You must use the Set keyword for objects. For example, if you are looking for a specific cell, declare a Range variable: Dim foundCell As Range.
  3. Attempt to Assign the Object: Use a method that might fail, such as .Find. For example: Set foundCell = Range("A1:A100").Find(What:="TargetValue"). If "TargetValue" does not exist in that range, VBA assigns Nothing to the foundCell variable.
  4. Implement the If Not Is Nothing Check: Immediately after the assignment attempt, wrap your subsequent logic in the check. Write: If Not foundCell Is Nothing Then. This tells VBA: "If it is NOT true that this object is empty, then proceed."
  5. Define the Success Action: Inside the If block, place the code you want to run if the object was found. For example: MsgBox "Found at " & foundCell.Address.
  6. Handle the Failure (Optional): Add an Else statement to handle cases where the object is indeed Nothing. For example: Else MsgBox "Value not found.".
  7. Close the Block: End the logic with End If to prevent "Block If without End If" compile errors.

Common Mistakes

One of the most frequent errors is attempting to use a standard comparison operator like = instead of Is. In VBA, = compares values, while Is compares object references. Writing If foundCell = Nothing Then will trigger a "Object variable or With block variable not set" error or a Type Mismatch because you cannot use the equals sign to check for the absence of an object.

Another common mistake is forgetting the Set keyword during assignment. If you write foundCell = Range("A1").Find("Value") without the Set keyword, VBA will try to assign the value of the found cell to the object variable rather than the object itself, leading to a runtime error. Remember: Objects always require Set.

Developers also frequently forget to handle the Nothing state entirely. If you attempt to access a property of an object (e.g., foundCell.Value) when foundCell is Nothing, the code will crash instantly with Runtime Error 91. The If Not ... Is Nothing pattern is the primary defense against this specific crash.

Tips

When working with complex projects, consider creating a helper function to handle these checks if you find yourself repeating the same If Not ... Is Nothing block dozens of times. This keeps your main procedure clean and readable.

If you are searching for an object across multiple sheets, always ensure your variable is declared at the top of the procedure. This ensures the object persists throughout the loop until you manually set it to Nothing or the procedure ends.

Use the Option Explicit statement at the very top of your module. This forces you to declare all variables, which prevents typos in your object names that could lead to a variable being unexpectedly Nothing because you misspelled it in one part of the code.

When you are finished using an object variable in a very large loop, it is good practice to manually clear it using Set myObject = Nothing. While VBA generally handles memory management, explicitly clearing large object references can prevent memory leaks in extremely complex automation tasks.

Troubleshooting

If your code is skipping the If Not ... Is Nothing block even though you are sure the item exists, check your .Find parameters. The .Find method remembers the settings from the last time you used the Excel Find dialog box (like "Match Case" or "Match Entire Cell Contents"). If those are set incorrectly, the method will return Nothing. Explicitly define these arguments in your code, such as LookIn:=xlValues, LookAt:=xlPart.

If you receive a "Type Mismatch" error on the line containing Is Nothing, verify that the variable you are checking is actually declared as an object. If you declared it as a String or Integer, the Is Nothing check is invalid because primitive data types are never Nothing; they have default values like empty strings ("") or zero (0).

If the code enters the If block but then crashes on the next line, check if the object was destroyed or became invalid between the check and the usage. This is rare in single-threaded VBA but can happen if you are interacting with external applications or volatile objects that can be closed by the user during execution.

Frequently Asked Questions

Why can't I just use If myObject = Nothing?

In VBA, the equals sign is for comparing values (like 5 = 5). Objects are pointers to memory locations. The Is keyword is specifically designed to compare these pointers to see if they point to the same instance or to the Nothing state.

What is the difference between Nothing and an empty string?

Nothing means the object variable does not point to any instance of an object at all. An empty string ("") is a valid value of a String variable. You use Is Nothing for objects and = "" for text.

Do I need to use Not if I want to find something that is missing?

No. If you want to execute code only when an object is NOT found, simply remove the Not: If myObject Is Nothing Then. This will trigger the code block only when the assignment failed.

Does this work for Worksheets and Workbooks?

Yes. Any variable declared as an object—including Workbook, Worksheet, Chart, and Range—must be checked using the Is Nothing syntax before accessing its properties.

Can I use this with a Collection or Array?

You cannot use Is Nothing on the array itself to see if it is empty. For arrays, you typically check if they are initialized using IsArray() or by handling errors with On Error Resume Next when checking the upper bound. However, if the array contains objects, you can use Is Nothing on the individual elements within the array.