Handling Object with collection


Sometimes, it is tricky to handle when you have to instance multiple objects during run time. However, you can apply this simple trick to automatically add custom objects to a collection.

Add these code into your module:

Option Explicit

Public obj_id As Integer
Public obj_col As collection

Sub test()

Dim c As Class1
Dim i As Integer
Dim obj As Object
Set obj_col = New collection
obj_id = 0

For i = 1 To 50
    Set c = New Class1

For Each obj In obj_col

'release resources
Set obj_col = Nothing
End Sub

Add a new class module called “class1”. Within class1, add these code:

Private id As Integer

Private Sub Class_Initialize()
obj_id = obj_id + 1
id = obj_id
obj_col.Add Me, CStr(id)
End Sub

Public Sub sayhi()
Debug.Print "id:" & id
End Sub

Now try to run sub test().

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s