Smart Systems for Home

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

Excel VBA Not Nothing: How to Check Object References

· 6 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 in Excel VBA is not nothing, use the If Not [ObjectName] Is Nothing Then syntax. This specific logical check is used to verify that an object variable has been successfully instantiated or assigned to a valid object before you attempt to call its properties or methods, which prevents the common "Object variable or With block variable not set" runtime error.

In VBA, when you declare an object variable (such as a Range, Worksheet, or Workbook), it is initially initialized to Nothing. This is a special value indicating that the variable does not currently point to any actual object in the Excel application. Attempting to perform an action on a variable that is Nothing will cause your macro to crash. By using the Not...Is Nothing pattern, you create a safety gate that ensures the code only proceeds if the object actually exists 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).
  • A workbook containing data or sheets you wish to reference via code.

Step-by-Step

  1. Open the Visual Basic Editor: Press ALT + F11 on your keyboard to launch the VBA environment. If you are on a Mac, you may need to use the Developer tab and click the Visual Basic icon.
  2. Insert a New Module: Go to the Insert menu and select Module. This provides a clean space to write your procedure.
  3. Declare Your Object Variable: At the top of your subroutine, declare the object you intend to use. For example, if you are searching for a specific cell, use Dim myRange As Range. Note that using Dim only creates the variable; it does not assign it to a real cell yet.
  4. Attempt to Assign the Object: Use a method that might fail, such as .Find. For example: Set myRange = Range("A1:A100").Find(What:="TargetValue"). The Set keyword is mandatory when assigning objects in VBA.
  5. Implement the "Not Nothing" Check: Immediately after the assignment attempt, write an If statement to verify the result. The syntax must be: If Not myRange Is Nothing Then. This reads as "If it is NOT the case that myRange is nothing," which logically means "If myRange actually contains an object."
  6. Place Actionable Code Inside the Block: Indent your code inside the If...End If block. For example, if the range was found, you might want to select it or change its color: myRange.Interior.Color = vbYellow.
  7. Handle the "Nothing" Scenario (Optional): Use an Else statement to define what happens if the object was not found. For example: Else MsgBox "The value was not found in the specified range.".
  8. Close the Block: Ensure you end the statement with End If to maintain the structure of the subroutine.

Common Mistakes

One of the most frequent errors is forgetting the Set keyword. In VBA, standard variables (like Integers or Strings) are assigned using a simple equals sign (x = 5). However, objects require Set x = Object. If you omit Set, VBA will attempt to assign the default property of the object to the variable rather than the object itself, often leading to a type mismatch error.

Another common mistake is using the wrong comparison operator. Beginners often try to use If myRange <> Nothing Then. This will result in a compile error because Nothing is not a value that can be compared using standard inequality operators; it is a state of the pointer. You must use the Is keyword (Is Nothing) to check for this state.

Additionally, developers sometimes place the Not Nothing check too late in the code. If you call myRange.Value before checking if myRange Is Nothing, the code will crash the moment it hits that line, making the subsequent check useless. The check must always precede the first usage of the object's properties.

Tips

To make your code cleaner, especially when dealing with multiple object checks, consider using a "Guard Clause." Instead of wrapping your entire logic in a giant If Not...End If block, you can exit the subroutine early if the object is nothing. For example: If myRange Is Nothing Then Exit Sub. This reduces indentation and makes the remaining code easier to read.

When working with complex loops, always explicitly set your object variables back to Nothing once you are finished with them, using Set myRange = Nothing. While VBA generally handles memory management, explicitly clearing object references is a best practice that prevents memory leaks in very large, long-running macros.

If you are checking for the existence of a worksheet by name, remember that the Worksheets("Name") syntax will throw an error immediately if the sheet doesn't exist, before you even get to the Is Nothing check. To handle this, you should use a custom function with On Error Resume Next to attempt the assignment and then check if the resulting object Is Nothing.

Troubleshooting

If you receive the error "Object variable or With block variable not set" (Runtime Error 91) despite having a check in place, verify that you haven't accidentally reset the variable elsewhere in your code. Check for any lines where the variable is reassigned or cleared.

If your If Not...Is Nothing block is being skipped even though you believe the object should exist, use the Debug.Print command or the Immediate Window (Ctrl + G) to inspect the variable. Type ? myRange.Address in the Immediate Window while the code is paused at a breakpoint to see if the object is actually pointing where you think it is.

If you are experiencing a "Type Mismatch" error on the line where you perform the check, ensure that the variable was declared as an Object or a specific object type (like Range or Worksheet). If the variable was declared as a Variant, the Is Nothing check still works, but you must ensure the variable was intended to hold an object and not a simple value like a string or number.

Frequently Asked Questions

What is the difference between Nothing and Empty?

Nothing is used specifically for object variables to indicate they don't point to an instance. Empty is used for Variant variables that have been declared but not yet initialized with any value of any type.

Can I use Not Nothing with a String?

No. Strings are not objects; they are primitive data types. To check if a string is not empty, use If myString <> "" Then or the Len(myString) > 0 check.

Why do I need the Not keyword?

The Is Nothing expression returns True if the object is missing. Since you usually want to run your code when the object is present, you use Not to flip the result to True when the object is valid.

Does this work for UserForms?

Yes, if you are dynamically loading a UserForm into a variable, you can use If Not myForm Is Nothing Then to ensure the form was successfully initialized before calling .Show.

Is there a shorter way to write this?

In standard VBA, the If Not ... Is Nothing syntax is the official and most reliable method. While some languages have "null-coalescing" operators, VBA requires this explicit conditional check.