Reputation: 101
Consider the following code:
Sub NestedCollections()
Dim col1 As Collection
Dim col2 As Collection
Dim col3 As Collection
Set col1 = New Collection
Set col2 = New Collection
Set col3 = New Collection
col2.Add "a"
col2.Add "b"
col2.Add "c"
col3.Add "d"
col3.Add "e"
col3.Add "f"
col1.Add col2
col1.Add col3
col1.Item(2).Add col3
Set col1 = Nothing
Set col2 = Nothing
Set col3 = Nothing
End Sub
If you add watch to "col1", and expand "item(2)", you'll notice that "item(4)" keeps on expanding. Why is this happening?
Cheers, Marek
Upvotes: 4
Views: 263
Reputation: 71177
Everything works normally, up until col1.Item(2).Add col3
is executed.
Beyond that, col1.Item(2)
is col3
as per this instruction:
col1.Add col3
By adding col3
to col1.Item(2)
, you're adding a pointer to col3
to... col3
, which is why it "keeps expanding" - the 4th item of col3
is col3
itself:
col3.Add "d" 'col1.Item(2)(1)
col3.Add "e" 'col1.Item(2)(2)
col3.Add "f" 'col1.Item(2)(3)
col3.Add col3 'col1.Item(2)(4)
I wouldn't recommend using such a recursive data structure (i.e. adding a collection to itself).
Upvotes: 6