Why Do I Need to Set Objects to Nothing in VBA?
Everyone knows you need to set object variables to nothing in VBA, right? ... Right?
I received a version of the following question from a reader the other day:
Why do I need to set objects to Nothing? Something about releasing resources. Doesn't seem to affect performance.
Here's a modified version of my response, with links to some useful articles on the topic:
Generally speaking, you don't usually need to explicitly set object variables to Nothing in VBA as the language cleans them up automatically when the procedure exits.
Technically speaking, VBA takes care of incrementing the COM reference count when an object is created and decrementing the reference count when the object variable goes out of scope. One thing you do need to be careful to avoid is creating circular references, though that's mostly an issue if you have pairs of classes that refer to each other via something like a.Parent
and.Child
class property.
Referenced articles
Cover image created with Microsoft Designer