Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a collection of dictionaries in VBA?

I'm trying to build up a collection of dictionaries in VBA. After the collection has been built, it will be converted to JSON, and sent to a web service in a HTTP request.

Because dictionaries are objects, they are added to the collection by reference, not by value. The result is that my collection is made up of identical dictionaries, rather than the individual dictionaries that I wanted.

Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset

Set qdf = CurrentDb.QueryDefs("qryTutors")
Set rs = qdf.OpenRecordset

Dim tutors As New Collection

If Not (rs.EOF And rs.BOF) Then
    Do Until rs.EOF = True
        Dim tutor As New Scripting.Dictionary
        tutor.Add "TutorName", rs!TutorFirstName.Value & " " & rs!TutorSurname.Value
        tutor.Add "TutorEmail", rs!TutorEmail.Value
        tutor.Add "TutorSubject", rs!TutorSubject.Value
        tutors.Add tutor
        tutor.RemoveAll
        rs.MoveNext
    Loop
End If

txtOutput.Value = JsonConverter.ConvertToJson(tutors)

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

Any help appreciated, thanks.

like image 368
Samuel Booth Avatar asked Sep 18 '25 19:09

Samuel Booth


1 Answers

Use a new dictionary in each iteration:

Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset

Set qdf = CurrentDb.QueryDefs("qryTutors")
Set rs = qdf.OpenRecordset

Dim tutors As New Collection
Dim tutor As Scripting.Dictionary

If Not (rs.EOF And rs.BOF) Then
    Do Until rs.EOF = True
        Set tutor = New Scripting.Dictionary
        tutor.Add "TutorName", rs!TutorFirstName.Value & " " & rs!TutorSurname.Value
        tutor.Add "TutorEmail", rs!TutorEmail.Value
        tutor.Add "TutorSubject", rs!TutorSubject.Value
        tutors.Add tutor
        rs.MoveNext
    Loop
End If

txtOutput.Value = JsonConverter.ConvertToJson(tutors)

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
like image 118
Florent B. Avatar answered Sep 21 '25 13:09

Florent B.