I have an issue when populating a collection in VBA in MS Access.
Here's the code I have:
Private Sub loadInfo()
Dim sql As String
sql = "SELECT * FROM table2';"
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)
With rs
.MoveFirst
While rs.EOF = False
Dim person As New person
Dim idToString As String
idToString = rs.Fields("ID").value
person.setFirstName (rs.Fields("first_name").value)
person.setLastName (rs.Fields("last_name").value)
people.Add person, idToString
.MoveNext
Wend
End With
End Sub
The collection is declared an initialized at the top of the class module. I can add items to it just fine. However, at the end of the Sub, I end up with a collection with the right amount of objects (however many I have in the Recordset,) but all of them with the same firstName and lastName.
Now, I thought that every time the "when" loop goes 'round, the variables inside of it would go out of scope, thus becoming null. In this case, that does not seem to be the case. Every time it gets back to person.setFirstName
, the firstName
of the item already in the collection changes to whatever the current firstName
of the new row is. The same goes for lastName
.
This leads me to believe that person
is not being created every time the loop goes 'round, giving me a collection of similar entries, aside from their key which is unique.
Any ideas as to how to get the loop to perform as it should?