(Solved) – Assign an object to an array within a loop in VBA

(solved)-–-assign-an-object-to-an-array-within-a-loop-in-vba

I try to create objects and put them into an array as follows. The problem is that all cells seem to have the same object in the end.

Sub foo()
    Dim Arr(1 To 3) As Class1
    Dim i As Integer
    For i = 1 To 3
        Dim obj As New Class1
        obj.name = i
        Set Arr(i) = obj
    Next
    For i = 1 To 3
        Debug.Print Arr(i).name 
    Next
End Sub

Surprisingly, the output is

3
3
3

The only explanation I can think of is that obj is not a local variable with respect to the loop.

I have also tried to remove the Set and instead have Arr(i) = obj. That results in Object variable or with block variable not set.

Leave a Reply

Your email address will not be published. Required fields are marked *