Search code examples
arraysvbareference

strange behavior : How elements are inserted in vba arrays?


Can any one explain me the following code behavior ?? -->

Public Type User
    firstName          As String
    lastName           As String
End Type

Sub test()
    Dim userList(1) As User
    Dim user1       As User
    user1.firstName = "Tom"
    user1.lastName = "Hanks"
    
    userList(0) = user1
    Debug.Print "0 userList(0).firstName=" & userList(0).firstName & " userList(0).lastName=" & userList(0).lastName
    user1.lastName = "Cruise"
    Debug.Print "1 userList(0).firstName=" & userList(0).firstName & " userList(0).lastName=" & userList(0).lastName

End Sub

And the console displays :

0 userList(0).firstName=Tom userList(0).lastName=Hanks
1 userList(0).firstName=Tom userList(0).lastName=Hanks

So my question is : why the console does not display

1 userList(0).firstName=Tom userList(0).lastName=Cruise

?

It looks like if vba insert a copy of the object I want to insert but not the original object.

Thanks for your answers.

This problem just happend, I did not succeed to solve it, but if I can't probably I will change my code so that all the initialization of the object will be done before the insertion in the array, but it is not very clean IMHO.


Solution

  • Ok I think I understand my mistake thanks to Ike and GSerg comments : indeed I assumed a user defined type behaved like a classic object but no, and if I consider it behaves like a primitive type, all becomes clear.