VB6 / VBA uses a deterministic approach to destroy objects. Each object stores the number of references to itself. When the number reaches zero, the object is destroyed.
Object variables are guaranteed to be cleared (set to Nothing ) when they go out of scope, this reduces the reference counts in their respective objects. No manual action required.
There are only two cases where explicit cleanup is required:
If you want the object to be destroyed before its variable goes out of scope (for example, your procedure will take a long time and the object stores the resource, so you want to destroy the object to free the resource as soon as possible).
If you have a circular link between two or more objects.
If objectA stores references to objectB , and objectB stores references to objectA , these two objects will never be destroyed unless you lock the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing .
The code snippet shown is incorrect. No manual cleaning required. Even manual cleanup is even harmful, as it gives you a false sense of a more correct code .
If you have a variable at the class level, it will be cleared / destroyed when the class instance is destroyed. You can destroy it earlier if you want (see Clause 1. ).
If you have a variable at the module level, it will be cleared / destroyed when your program exits (or, in the case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see Clause 1. ).
The access level of a variable (public vs. private) does not affect its lifetime.
GSerg Sep 26 '13 at 9:18 2013-09-26 21:18
source share