Search code examples
excelvbaloopsclasscollections

VBA : How to access to a class instance when that class is in a collection which is in a class which is in a collection?


I have a very complex data structure but I want to see how vba react to this.

Public Sub Search()
Dim i As Long, j As Long, number_program As Long, index As Long: index = 1

For i = 1 To Element.Count
    While //something
        If //something
            Dim new_operation As Class3
            Set new_operation = New Class3
            index = index + 1
            new_operation.value1 = 1
            new_operation.value2 = 2
            Element(i).operations.Add new_operation
        End If
        //something giving a value to number_program
        If number_program > 0 Then
            Element(i).operations(index).value3 = 3
        End If 
    Wend
    index = 1
Next i

End Sub

So here Element(i) is a Class which is in the Collection named Element. The object Element(i).operations is a Collection and in this collection I will have an undefined number of class Element(i).operations(j).

I got the error : Error of execution '9' : the index does not belong to the selection onto this line : Element(i).operations(index).value3 = 3

Later in my code I have this line : Articles_triés(i).operations(j).Count which also gives an error

The only thing that can be wrong may be the declaration of my collection in the Element(i) class :

Private m_operations As Collection

Public Property Get operations_article() As Collection
    If m_operations Is Nothing Then
        Set m_operations = New Collection
    End If
    Set operations = m_operations
End Property

Private Sub Class_Initialize()
    Set m_operations = New Collection
End Sub

Note that every variable is defined and accessible even if I did not show all the variable initialiaztions.


Solution

  • In your first code index is upfront of the number of elements of operations. Try to implement this:

    Public Sub Search()
      Dim i As Long, j As Long, number_program As Long, index As Long
      For i = 1 To Element.Count
        index = 0 ' suppose operations is empty
        While //something
            If //something
                Dim new_operation As Class3
                Set new_operation = New Class3
                index = index + 1
                new_operation.value1 = 1
                new_operation.value2 = 2
                Element(i).operations.Add new_operation
            End If
            //something giving a value to number_program
            If number_program > 0 Then
                Element(i).operations(index).value3 = 3
            End If 
        Wend
      Next i
    End Sub