On 11 Mar, 16:50, "Bob Phillips" wrote:
"deltaquattro" wrote in message
...
Thank you very much, Bob: I understand that I can safely delete the
line
Set Inst = Nothing
Two somehow related questions:
1. In the following code
Sub foo()
Dim Coll As Collection
Dim Inst As Class1
Set Coll = New Collection
MsgBox Coll.Count
Set Inst = New Class1
Inst.InstName = "test"
Coll.Add Item:=Inst
MsgBox Coll.Count
End Sub
each time I rerun the code, a new Coll object is created, as confirmed
by the fact that the first MsgBox shows 0 *and the second 1. Now, are
the old objects deleted when execution is completed? Or am I filling
the memory of my PCs with many Collection objects, so I need to Set
Coll = Nothing before End Sub?
VB has a built-in facility called garbage collection which tidies up after
us. When an object goes out of scope, its memory is released, that is why
collection is a new object each time (actually Coll would be initialised
anyway, as you explicitly New it). So no, you are not filling memory with
many instances of that objectr, which is the point I was making in my irst
response.
Because of garbage collection, you do not need to Set Coll = Nothing,
although IMO it is a good prcatice to do so, you cannot be sure that all
languages release memory, or do it properly, and it takes little effort to
type it.
You could get paranoid, you could set all strings to "", but I don't
advocate this :-)
2. If I set a Collection to Nothing, is the space occcupied by it
released or not? For example,
Sub foobar()
Dim Coll As Collection
Dim Inst As Class1
Dim I As Long
Set Coll = New Collection
For I = 1 To 100000
* * *Set Inst = New Class1
* * *Inst.InstName = CStr(I)
* * *Coll.Add Item:=Inst
Next I
Set Coll = Nothing
End Sub
Yes of course, that is what that command does.
Hi Bob,
thanks a lot, it's much clearer now! Sorry if my questions can be
somewhat naive, but I just started learning OOP this year by myself,
using VBA, so there's a lot of things I don' know about objects,
collections, garbage collection (fancy name :) etc. Luckily, your
answers are helping me a lot to understand the subject :)
Ciao
deltaquattro