vba - 如何在 Class B 中定义和使用 Class 的集合

标签 vba class collections

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

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

' 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

这自然会产生错误:变量未定义(参见上面的评论)

最佳答案

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

 Private colPersons As New Collection

不应放置在声明其他属性(property)之后(此处未显示:地址和收入)

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

关于vba - 如何在 Class B 中定义和使用 Class 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924451/

相关文章:

vba - 使用 VBA 更新 Excel 切片器选择的性能较差

vba - 宏来计算 hh :mm:ss 中的差异

对象数组的C++方法

c++ - 嵌套类的成员函数返回嵌套类的类型

java - List#copyOf、Set#copyOf 和 Map#copyOf 与传统方法有什么区别?

java - Guava 依赖的 Jar 大小 - 有小版本吗?

vba - Excel VBA 内存不足

java - 如何在Java中加载和使用第三方.dll的功能

javascript - 在 JavaScript 中创建 onclick 类的新实例的正确方法是什么?

java - 如何从另一个列表中替换对象列表中的元素