Smart Systems for Home

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

Excel VBA Set Nothing: How to Clear Object Variables

· 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 use Set variable = Nothing in Excel VBA, you assign the Nothing keyword to an object variable to break the reference to the object it was previously pointing to. This is primarily used to release memory and ensure that the VBA environment does not hold onto resources—such as Workbooks, Worksheets, or Ranges—longer than necessary, which prevents memory leaks and potential application crashes during long-running macros.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • The Developer tab enabled in the Excel Ribbon.
  • Basic knowledge of how to open the Visual Basic Editor (VBE) using Alt+F11.
  • An existing VBA module where you are declaring object variables.

Step-by-Step

  1. Open the Visual Basic Editor: Press Alt + F11 on your keyboard while in Excel to open the VBE window.
  2. Insert a Module: If you don't have one, go to the Insert menu and select Module. This is where your code will reside.
  3. Declare Your Object Variables: You must use the Dim statement to declare variables that will hold objects. For example, declare a variable for a worksheet and a workbook:
    Dim wb As Workbook
    Dim ws As Worksheet
  4. Assign Objects Using the Set Keyword: In VBA, you cannot assign an object to a variable using a simple equals sign; you must use Set. For example, assign the active workbook and a specific sheet:
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
  5. Perform Your Operations: Write the logic of your macro. For instance, you might write data to a cell or format a range using the ws variable:
    ws.Range("A1").Value = "Hello World"
  6. Clear the Object References: Once the operations involving these objects are complete, use the Set [Variable] = Nothing syntax. This tells VBA that you no longer need the reference to those specific objects:
    Set ws = Nothing
    Set wb = Nothing
  7. Verify the Result: If you attempt to use the variable after setting it to Nothing (e.g., Debug.Print ws.Name), VBA will throw a "Run-time error '91': Object variable or With block variable not set," confirming that the reference has been successfully cleared.

Common Mistakes

One of the most frequent errors is forgetting the Set keyword when assigning Nothing. Writing ws = Nothing instead of Set ws = Nothing will result in a compile error because VBA expects the Set keyword whenever you are dealing with object references rather than simple data types like Integers or Strings.

Another common mistake is attempting to clear a variable that was never initialized. If you declare Dim ws As Worksheet but never actually assign it a value using Set ws = ..., the variable is already Nothing by default. While calling Set ws = Nothing on an uninitialized variable won't cause a crash, it is redundant code that adds unnecessary lines to your script.

Users also often confuse Nothing with an empty string ("") or a zero. In VBA, Nothing is a specific state for object variables indicating the absence of an object. Using ws = "" on a Worksheet object will trigger a type mismatch error because a worksheet object cannot be converted into a string.

Finally, some developers place the Set Nothing commands inside a loop that is still utilizing the object. If you clear the reference to a worksheet while you are still iterating through its rows, the code will fail immediately upon the next attempt to access that worksheet.

Tips

To make your code more robust, always place your Set Nothing statements at the very end of your procedure, ideally within an error handling block. If your code crashes halfway through, the standard cleanup lines at the bottom might be skipped. By using a CleanUp: label and a GoTo CleanUp statement in your error handler, you ensure that memory is released regardless of whether the macro finished successfully or encountered an error.

When working with large-scale projects involving hundreds of objects or external applications (like Word or Outlook automation), clearing objects is not just a best practice—it is essential. External applications often remain running as "ghost processes" in the Windows Task Manager if the VBA object reference is not explicitly set to Nothing and the application is not closed.

Consider using the With...End With block to reduce the number of times you have to reference an object. While this doesn't replace the need for Set Nothing, it makes your code cleaner. Once the End With is reached, you can then clear the primary object variable used in the block.

If you are using a global or module-level variable, be extra cautious. Since these variables persist for the duration of the Excel session, failing to set them to Nothing can lead to significant memory bloat over time, especially if the macro is run repeatedly without restarting Excel.

Troubleshooting

If you encounter a "Run-time error '91': Object variable or With block variable not set," it means you are trying to access a property or method of an object that is currently Nothing. To fix this, check if you have already called Set variable = Nothing earlier in the code or if the initial Set command failed to find the object (for example, if you tried to set a variable to a sheet name that doesn't exist).

If your Excel application feels sluggish or crashes after running a macro that uses many objects, check your Task Manager (Ctrl+Shift+Esc). If you see multiple instances of Excel or other Office apps running despite having closed them, it is a sign that you are not properly using Set Nothing to release those object references. Review your code and ensure every Set has a corresponding Set ... = Nothing.

When debugging, use the Locals Window (View > Locals Window in the VBE). This window allows you to monitor the state of your variables in real-time. As you step through your code with F8, you can watch the variable change from a specific object (like Worksheet) to Nothing. If the variable remains as an object after your cleanup line, verify that you are targeting the correct variable name.

Frequently Asked Questions

Do I need to use Set Nothing for every single variable?

No. You only use Set Nothing for object variables (Workbooks, Ranges, Sheets, Collections). Standard data types like Integer, String, Boolean, and Double do not use the Set keyword and are cleared automatically when the procedure ends.

Does VBA automatically clear objects when a sub ends?

In most simple cases, VBA's garbage collection will handle local variables once the procedure finishes. However, relying on this is risky for complex objects, external application instances, or module-level variables, which is why explicit clearing is recommended.

What is the difference between Set Nothing and clearing a cell?

Set Nothing affects the VBA variable in the computer's memory, not the data in the Excel spreadsheet. To clear the contents of a cell, you would use Range("A1").ClearContents. Setting a Range variable to Nothing simply means the variable no longer "points" to that cell; it does not delete the data in the cell.

Can I use Set Nothing on a Collection or Dictionary?

Yes. Collections and Dictionaries are objects. When you are finished with a large collection, using Set myCollection = Nothing helps release the memory occupied by that collection and all the objects contained within it.

Will Set Nothing slow down my code?

No. The time it takes to set a reference to Nothing is negligible. The performance benefit gained from preventing memory leaks and reducing the overhead on the system far outweighs the microscopic time spent executing the command.