Hi Aidy
It all depends upon scope. When a user created (instantiated) object goes
out of scope and there are no references to it the VBA will delete it for
you.
Take the following procedure:
Public Sub MyProc()
Dim mcItem as MyClass
' Create an object based on a class called MyClass
Set mcItem = New MyClass
' Do something with mcItem here
End Sub
When the procedure exits VBA will destroy mcItem.
Public Sub MyProc()
Dim mcItem as MyClass
Dim mcItem2 as MyClass
' Create an object based on a class called MyClass
Set mcItem = New MyClass
' Create a reference to the above object (NOT a new object)
Set mcItem2 = mcItem
' Do something with mcItem/mcItem2 here
' Dereference mcItem from the object
Set mcItem = Nothing
' The object still exists because mcItem2 still
' has a reference to it
' This deletes the object
Set mcItem2 = Nothing
End Sub
In the above a new object is created (mcItem) and a second reference is
made to that object (mcItem2). So when the first reference (mcItem) is
deleted the object is not deleted because mcItem2 still holds a reference
to it. When we dereference mcItem2 then the object is deleted.
<---- All this code is in the same module--->
Private mmcItem as MyClass
Public Sub MyProc()
' Create an object based on a class called MyClass
Set mmcItem = New MyClass
MyOtherProc
End Sub
Public Sub MyOtherProc()
' Do something with mmcItem
End Sub
In the above the variable mmcItem is defined at Module level, so can be
"seen" by any procedure in that module. Once the procedure MyProc has
actually created it (instantiated it) it can be used by any other procedure
in the module. It stays in existance while any code in that module is
running. As soon as code in that module stops VBA will delete the object
for you automatically.
This is just skimming the surface, but I hope it helps a little. Also check
out the VBA online help and investigate Sub/Function/Public/Friend/Private
etc. to get a better idea about all this.
HTH rather than confuses - Peter
(e-mail address removed) (Aidy) wrote in