VBA Classes - How to have a class hold additional classes

后端 未结 3 1293
刺人心
刺人心 2020-12-29 14:29

I have a challenge that I am trying to solve using classes.

I am logging transactions into a class.

Each transaction has the following:

  • Name
3条回答
  •  臣服心动
    2020-12-29 14:34

    There are a few things that don't do what you expect in your code. I have cleaned it a bit and this new version should be closer to what you want. Let me know if the changes are not self-explanatory.

    Main procedure:

    Sub test()
    
        Dim i As Long
        Dim j As Long
    
        'code to populate some objects
        Dim clocklist As Collection
        Dim clock As classClocks
        Dim businessContactList As Collection
        Dim businessContact As classBusinessContact
    
        Set clocklist = New Collection
    
        For i = 1 To 3
            Set businessContactList = New Collection
            Set clock = New classClocks
            clock.LawyerName = "lawyer " & i
            For j = 1 To 3
                Set businessContact = New classBusinessContact
                businessContact.Name = "Business Contact " & j
                businessContactList.Add businessContact
            Next j
            Set clock.BusinessContactAdd = businessContactList
            clocklist.Add clock
        Next i
    
        Set businessContactList = Nothing
    
        'write the data backout again
        For Each clock In clocklist
            Debug.Print clock.LawyerName
            Set businessContactList = clock.BusinessContacts
            For Each businessContact In businessContactList
                Debug.Print businessContact.Name
            Next
    
        Next
    
    End Sub
    

    classClocks:

    Private pLawyerName As String
    Private pBusinessContactList As Collection
    
    Private Sub Class_Initialize()
      Set pBusinessContactList = New Collection
    End Sub
    
    Public Property Get LawyerName() As String
        LawyerName = pLawyerName
    End Property
    
    Public Property Let LawyerName(ByVal sLawyerName As String)
        pLawyerName = sLawyerName
    End Property
    
    Public Property Get BusinessContacts() As Collection
        Set BusinessContacts = pBusinessContactList
    End Property
    
    Public Property Set BusinessContactAdd(contactCollection As Collection)
    
        For Each contactName In contactCollection
            pBusinessContactList.Add contactName
        Next
    
    End Property
    

提交回复
热议问题