Creating Nested Class

后端 未结 2 1537
独厮守ぢ
独厮守ぢ 2021-01-07 00:29

I am trying to create a nested class in VBA.

So far I have successfully created the following:

OurCompany.Department.Employee("Jo         


        
2条回答
  •  无人及你
    2021-01-07 00:55

    I strongly suggest to read the answer in this post including any attached references.

    Nevertheless, a simple implementation could be as follows.

    Company Class:


    Option Explicit
    Private mDepartmentsList As Object
    
    Public Property Get Department(ByVal StringKey As String) As Department
        With mDepartmentsList
            If Not .Exists(StringKey) Then
                Dim objDepartment As New Department
                .Add StringKey, objDepartment
            End If
        End With
    
        Set Department = mDepartmentsList(StringKey)
    End Property
    
    Public Property Get Keys() As Variant
        Keys = mDepartmentsList.Keys
    End Property
    
    Private Sub Class_Initialize()
        Set mDepartmentsList = CreateObject("Scripting.Dictionary")
    End Sub
    
    Private Sub Class_Terminate()
        Set mDepartmentsList = Nothing
    End Sub
    

    Department Class:


    Option Explicit
    Private mEmployeesList As Object
    
    Public Property Get Employee(ByVal StringKey As String) As String
        Employee = mEmployeesList(StringKey)
    End Property
    
    Public Property Let Employee(ByVal StringKey As String, ByVal StringValue As String)
        mEmployeesList(StringKey) = StringValue
    End Property
    
    Public Property Get Keys() As Variant
        Keys = mEmployeesList.Keys
    End Property
    
    Private Sub Class_Initialize()
        Set mEmployeesList = CreateObject("Scripting.Dictionary")
    End Sub
    
    Private Sub Class_Terminate()
        Set mEmployeesList = Nothing
    End Sub
    

    Testing:


    Option Explicit
    
    Sub TestCompanyClass()
    
        Dim OurCompany As Company
        Set OurCompany = New Company
    
        With OurCompany
            .Department("Finance").Employee("John") = "Employee Number 100"
            .Department("Finance").Employee("Kim") = "Employee Number 101"
            .Department("Engineering").Employee("Sam") = "Employee Number 124"
        End With
    
        Dim d As Variant, e As Variant
        With OurCompany
            For Each d In .Keys
                Debug.Print "Department: " & d
                For Each e In .Department(d).Keys
                    Debug.Print vbTab & "Employee: " & e & " - " & .Department(d).Employee(e)
                Next e
            Next d
        End With
    
        Set OurCompany = Nothing
    End Sub
    

    Output:


    Department: Finance
        Employee: John - Employee Number 100
        Employee: Kim - Employee Number 101
    Department: Engineering
        Employee: Sam - Employee Number 124
    

提交回复
热议问题