Search code examples
arraysexcelvbacollections

Can I put a collection into a collection in vba?


I was looking for an answer on stack overflow but didn't find a good one.

Imagine that I have a first collection filled with 5 classes and those 5 classes contains a number (we will say 1, 2, 3, 4, 5 for the sake of example). Pretty basic data structure for now. My question is, is it possible that can those 5 classes of the first collection also contains a collection which is containing 3 names ("aaa", "bbb", "ccc" for example).

With this data structure I would access to the names with this syntax:

Collection_number_1(1).Class_1.Collection_number_2(1).names

I was just asking myself if this was possible in VBA. Sorry if i wasn't clear this was my first question on SO. Have a nice day !

I know that the equivalent is possible in C for example.


Solution

  • This is the general gist of what you need.

    In a normal module:

    Sub test()
        Dim cls As Class1
        
        Dim namearr(0 To 8) As String
        namearr(0) = "bob"
        namearr(1) = "jane"
        namearr(2) = "alex"
        namearr(3) = "jim"
        namearr(4) = "fred"
        namearr(5) = "jill"
        namearr(6) = "sam"
        namearr(7) = "tim"
        namearr(8) = "cass"
        
        Set cls = New Class1
        cls.init
        
        Dim i As Long
        For i = 0 To UBound(namearr)
            cls.add_data namearr(i)
        Next i
        
        Dim classcoll As Collection
        
        Set classcoll = New Collection
        
        classcoll.Add cls
        
        For i = 1 To classcoll(1).names.Count
            Debug.Print classcoll(1).names(i)
        Next i
        
    End Sub
    

    In a class module:

    Private namescoll As Collection
    
    Public Sub init() 'This could be a set to go with the get but I usually end up needing an init when doing similar things
        Set namescoll = New Collection
    End Sub
    
    Public Sub add_data(val)
        namescoll.Add val
    End Sub
    
    Public Property Get names() As Collection
        Set names = namescoll
    End Property
    

    I just named my class module Class1

    You can add as many class instances and collection elements as you want.