如何在ClassB中定义和使用ClassA的集合

时间:2017-01-29 18:31:11

标签: vba class collections

假设我有一个名为Person的类,具有Name和Age属性,以及另一个名为Family的集合,其中包含Income,Address和Persons集合等属性。 我找不到关于如何实现这个概念的完整例子。 此外,由于我是集合和类的新手,我在创建一个小子程序以使用这两个函数时也没有成功。

根据互联网上有限的资源,这是我最好的尝试:

' Inside the class Module Person .........................
Public pName As String 
Public pAge As Integer
Public Property Get Name() As String
 Name = pName
End Property
Public Property Let Name(value As String)
 pName = value
End Property

' Inside the class Module Family .........................
' ... Income and address Properties are supposed 
' ... declared and will not be used in this trial
Private colPersons As New Collection

Function AddP(aName As String, anAge As integer)
'create a new person and add to collection
 Dim P As New Person
 P.Name = aName
 P.Age = anAge
 colPersons.Add R ' ERROR! Variable colPersons not Defined!
End Function

Property Get Count() As Long
'return the number of people
Count = colPersons.Count
End Property

Property Get Item(NameOrNumber As Variant) As Person
'return this particular person
Set Item = Person(NameOrNumber)
End Property

现在尝试使用上述的子程序:

Sub CreateCollectionOfPersonsInsideAFamily()
'create a new collection of people
Dim Family_A As New Family
'add 3 people to it
Family_A.AddP "Joe", 13
Family_A.AddP "Tina", 33
Family_A.AddP "Jean", 43
'list out the people
Dim i As Integer
For i = 1 To Family_A.Count
Debug.Print Family_A.Item(i).Name
Next i
End Sub

当然这是错误的:变量未定义(参见上面的评论)

1 个答案:

答案 0 :(得分:2)

很抱歉给您带来不便......但问题是该行:

 Private colPersons As New Collection
在宣布其他属性之后不应该放置

(这里没有显示:地址和收入)

将此行放在其类顶部的声明区域后,所有代码都证明是正确的。