The direct answer: If Not rng Is Nothing Then is a VBA safeguard that checks whether an object variable (here, rng) actually refers to a valid range before your code tries to use it. If rng is unset or points to nothing, the condition is True (because Not ... Is Nothing negates the Is Nothing test), and the code inside the If block runs only when rng is a real Range object.
Why You Need This Check
In VBA, an object variable that hasn’t been assigned still exists—it holds the special value Nothing. If you try to call a method or read a property of a Nothing object, VBA raises error 91: “Object variable or With block variable not set.” That error stops your macro mid-run. The If Not rng Is Nothing pattern prevents this by testing the variable before any risky operation.
Common situations where rng might be Nothing:
- The user clicked Cancel in an
InputBoxwith type 8 (Range). - A
Range.Findcall found no match. - A function that returns a Range (like
Intersect) returnedNothing. - The variable was declared but never assigned.
How the Syntax Works
VBA’s Is operator compares two object references. rng Is Nothing returns True if rng holds no object reference. The Not operator flips that result, so Not rng Is Nothing is True exactly when rng points to a valid object. The full line is a standard conditional statement:
If Not rng Is Nothing Then
' rng is a valid Range – safe to use it
MsgBox rng.Address
End If
Note that Not has lower precedence than Is, so the expression is parsed as Not (rng Is Nothing). You can add parentheses for clarity: If Not (rng Is Nothing) Then. Both forms work identically.
Practical Examples
Here are two real-world uses that show why the check matters.
Example 1: InputBox that can be cancelled
Dim rng As Range
Set rng = Application.InputBox("Select a range", Type:=8)
If Not rng Is Nothing Then
MsgBox "You selected " & rng.Address
Else
MsgBox "You cancelled."
End If
If the user presses Cancel, InputBox returns Nothing (not an empty string), so the If correctly skips the message.
Example 2: Find a value
Dim rng As Range
Set rng = Sheet1.Range("A1:A100").Find(What:="Target")
If Not rng Is Nothing Then
rng.Select
Else
MsgBox "Target not found."
End If
Without the check, rng.Select would crash if the search failed.
Common Mistakes and Misconceptions
One frequent error is writing If rng <> Nothing Then. That is invalid because <> compares values, not object references. Only Is and IsNot (in some VBA versions) work with objects. Another mistake is forgetting to use Set when assigning a range: rng = Range("A1") causes a compile error. Always use Set rng = ....
A common misconception is that If Not rng Is Nothing also checks if the range is empty or contains no cells. It does not—it only verifies that the variable points to an existing Range object. An empty range (e.g., Range("A1:A0")) is still a valid object, so the condition would be True even though the range has no cells.
Alternatives and Related Patterns
Sometimes you need to check if a variable is Nothing before doing something else. The inverse pattern is:
If rng Is Nothing Then
' handle the no-range case
End If
For more complex logic, you can combine with ElseIf or use Select Case. There’s also the IsObject function, but it tests whether a variable is an object type, not whether it holds a reference—so it’s not a substitute for Is Nothing.
If you’re using VBA 6.0 or later (which includes Office 2010+), you can use the IsNot operator: If rng IsNot Nothing Then. This is clearer but less widely known. Both work.
Best Practices for Robust Code
Always declare object variables with an explicit type (Dim rng As Range) rather than Variant—this catches typos at compile time. After a Set that might fail, immediately check for Nothing. Also consider using On Error Resume Next only when you have no other option; the Is Nothing check is cleaner and avoids hiding other errors.
When you finish with an object, you can set it to Nothing to release memory, though VBA does this automatically when the procedure ends. Explicitly clearing is only necessary for global objects or when you want to force early cleanup.
Frequently Asked Questions
Q: What does Is Nothing actually mean?
It checks if an object variable currently holds no reference to any object. A declared but unassigned object variable is automatically set to Nothing.
Q: Can I use If rng Is Nothing with a string or number?
No. Is only works with object references. For strings or numbers, use = or <>.
Q: Why do I get error 91 even with the check?
If you get error 91 after the check, the variable might have been set to Nothing inside the block, or you’re using a different variable. Also, if you use Dim rng As Range but never Set it, the check correctly catches it—so the error would come from elsewhere.
Q: Does Not rng Is Nothing work in Microsoft Access or Word VBA?
Yes, the syntax is identical across all Office applications that support VBA. The object type might be Range in Excel, but in Word it would be a different object (e.g., Document). The pattern is the same.
Q: How do I test if a range is empty (no cells)?
Use If rng.Cells.Count = 0 Then or check rng.Count. But remember, a range like Range("A1") always has at least one cell, so emptiness usually refers to blank cells, which requires a different check like WorksheetFunction.CountA(rng) = 0.
Q: Is there a performance cost to using Is Nothing?
Negligible. It’s a simple reference comparison, far cheaper than the error handling it prevents.
Related
- Forecast Linear Excel: How to Use FORECAST.LINEAR
- Shortcut for Shutdown? The Real Windows Way
- Entry Level Data Entry Clerk: Job, Pay & Skills
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Outlook VBA: Select an Excel Worksheet by PathIn Outlook VBA on Windows, create an Excel application object, open the workbook by its full file path,…
- VBA Delete Whole Row: Safe Methods and ExamplesTo delete an entire worksheet row with VBA, use Rows(5).EntireRow.Delete, replacing 5 with the row number you want…
- Excel VBA Error Messages: Causes, Codes, and FixesAn Excel VBA error message means the macro could not compile, run an instruction, or complete an operation…
- VBA MsgBox OK Only: Syntax and Button OptionsYes. In Excel VBA, MsgBox displays an OK-only dialog by default, and you can make that choice explicit…
- Excel VBA: Loop Through Every Sheet in a Workbook SafelyTo run VBA on every worksheet in a workbook, use a For Each loop with the workbook’s Worksheets…
- Excel VBA Copy and Paste Cells: Examples and OptionsTo copy a cell with Excel VBA, use the source range’s Copy method and specify a destination: sourceCell.Copy…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.