I try to fill an array with objects that are created within a loop as follows. The problem is that all cells seem to have the same object in the end. The explanation might be that obj is not a local variable with respect to the loop.
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
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.
Dim Arr(1 To 3) As Class1The variable must be of Variant data type.Dim obj As New Class1You can't set a Dim statement in a loop. I don't know why it doesn't crash. Anyway, you name the sameobjasithree times. The lastI sticks. Of course,Set Arr(i) = obj` does assign this same0bjto 3 elements of Arr() and, you are right, it's the same object assigned to 3 elements of Arr().