对收藏的误解

时间:2017-02-22 09:44:30

标签: vba

根据这篇文章What are the benefits of using Classes in VBA?,我做了一些代码。 第一类 CarteID

Option Explicit

Private agePersonne As Long
Private nomPersonne As String

Public Property Get glAgePersonne() As Long
    glAgePersonne = agePersonne
End Property

Public Property Let glAgePersonne(lAgePersonne As Long)
    agePersonne = lAgePersonne
End Property

Public Property Get glNomPersonne() As String
    glNomPersonne = nomPersonne
End Property

Public Property Let glNomPersonne(lNomPersonne As String)
    nomPersonne = lNomPersonne
End Property

然后是第二课 ProcessCarteID

Option Explicit

Private colCartesID As Collection

Public Property Get gsCartesID() As Collection
    Set gsCartesID = colCartesID
End Property

Public Property Set gsCartesID(sCartesID As Collection)
    Set colCartesID = sCartesID
End Property

Function RecupAgeMoyen() As Double

    Dim cid As CarteID
    Dim moyenneAge As Double
    moyenneAge = 0

    For Each cid In colCartesID
            moyenneAge = moyenneAge + cid.glAgePersonne
    Next cid

    moyenneAge = moyenneAge / colCartesID.Count

    RecupAgeMoyen = moyenneAge

End Function

模块:

Option Explicit

Function PopulateArray() As Collection

    Dim colInfos As New Collection
    Dim cid As CarteID

    Set cid = New CarteID
    cid.glNomPersonne = "Fred"
    cid.glAgePersonne = 21
    colInfos.Add cid

    Set cid = New CarteID
    cid.glNomPersonne = "Julie"
    cid.glAgePersonne = 18
    colInfos.Add cid

    Set cid = New CarteID
    cid.glNomPersonne = "Jean"
    cid.glAgePersonne = 25
    colInfos.Add cid

    Set PopulateArray = colInfos

End Function

Sub TestAgeMoyen()

    Dim pci As ProcessCarteID

    Set pci = New ProcessCarteID
    Set pci.gsCartesID = PopulateArray()

    Debug.Print pci.RecupAgeMoyen()

End Sub

在函数RecupAgeMoyen()中,我尝试了For Each cid In colCartesIDFor Each cid In gsCartesID。两者都有效。

我只是想知道为什么它也适用于gsCartesID因为我不确定理解。

谢谢!

0 个答案:

没有答案