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 Next For Each obj In obj_col obj.sayhi Next '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().