I want to convert a range with two columns into a collection of dictionaries. For example, if the range is
A | B |
---|---|
1 | 2 |
3 | 4 |
5 | 6 |
then I want to have (using JSON notation) the collection [{first:1, second:2}, {first:3, second:4}, {first:5, second:6}]
.
I tried the following:
Function Make_Collection(r As Range) As Collection
Dim out_collection As New Collection
Dim row As Range
For Each row In r.Rows
Dim current_row As New Dictionary
current_row.Item("first") = row.Cells(1, 1).Value2
current_row.Item("second") = row.Cells(1, 2).Value2
out_collection.Add current_row
Next
Set Make_Collection = out_collection
End Function
but I get [{first:5, second:6}, {first:5, second:6}, {first:5, second:6}]
, that is three copies of the last row, instead of a dictionary for each row.
How can I fix this?
EDIT
Great answer by @QHarr below. In other words, I thought that my code was equivalent to
Function Make_Collection(r As Range) As Collection
Dim out_collection As New Collection
Dim row As Range
For Each row In r.Rows
Dim current_row As Dictionary
current_row = New Dictionary
current_row.Item("first") = row.Cells(1, 1).Value2
current_row.Item("second") = row.Cells(1, 2).Value2
out_collection.Add current_row
Next
Set Make_Collection = out_collection
End Function
but it is actually equivalent to
Function Make_Collection(r As Range) As Collection
Dim out_collection As New Collection
Dim row As Range
For Each row In r.Rows
Dim current_row As Dictionary 'Do nothing on second and later iterations
If current_row is Nothing Then 'True on first iteration only
Set current_row = New Dictionary
current_row.Item("first") = row.Cells(1, 1).Value2 'Change the object in place on
current_row.Item("second") = row.Cells(1, 2).Value2 'second and later iterations
out_collection.Add current_row 'Adds every time a reference to the same object
Next
Set Make_Collection = out_collection
End Function