I have a worksheet with this type of structure (there are more columns in the real sheet, but not many):
ColumnAValue1 ColumnBValue1 23
ColumnAValue1 C
Sub Test()
Dim c As Collection
Set c = New Collection
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim i As Long
For i = 1 To 10 'Assume 10 rows
AddToLayeredCollection c, ws.Cells(i, 3).value, ws.Cells(i, 1).value, ws.Cells(i, 2).value 'Assume two columns for keys, A and B
Next
'Add 'c' to the watch window and examine it
End Sub
Public Sub AddToLayeredCollection(ByVal root_collection As Collection, ByVal value As Variant, ParamArray keys() As Variant)
Dim i As Long
Dim target_collection As Collection
Set target_collection = root_collection
For i = LBound(keys) To UBound(keys)
Set target_collection = ResolveToCollection(target_collection, keys(i))
Next
target_collection.Add value
End Sub
Private Function ResolveToCollection(ByVal parent_collection As Collection, ByVal key As Variant) As Collection
On Error Resume Next
Set ResolveToCollection = parent_collection(key)(1)
On Error GoTo 0
If ResolveToCollection Is Nothing Then
Set ResolveToCollection = New Collection
parent_collection.Add Array(key, ResolveToCollection), key
End If
End Function
The only reason I'm using the Array()
thing is to be able to retrieve keys from the collection. You can use Dictionary instead and remove the Array()
.