嵌套的VBA类集合返回“参数不可选”错误

时间:2018-09-09 07:43:17

标签: vba class

我正在尝试用子类的集合来代表嵌套类的想法,并以祖母-已婚女儿-小孩子为例,所以我有3类,如下:

'级祖母:

Private pMarriedDaughter As Collection    
Public Property Get MarriedDaughter() As Collection
 MarriedDaughter = pMarriedDaughter
 End Property
Public Property Set MarriedDaughter(C As Collection)
 Set pMarriedDaughter = C
 End Property

'已婚妈妈班:

Private pChildren As Collection   
Public Property Get Children() As Collection   ' ERROR HERE!
 Children = pChildren
End Property  
Public Property Set Children(C As Collection)
 Set pChildren = C
End Property

'儿童班:

Private pName As String    
Public Property Get Name() As String
 Name = pName
End Property    
Public Property Let Name(s As String)
 Let pName = s
End Property

以及尝试填充类的主例程:

Sub TestGrandMother()

' Create 3 Childs
Dim Child_1a As New Child: Child_1a.Name = "Bill"
Dim Child_1b As New Child: Child_1b.Name = "Sam"
Dim Child_2a As New Child: Child_2a.Name = "Sahar"

' Create 2 Married Daughters:
Dim Mamy1 As New MarriedMom
Dim Mamy2 As New MarriedMom

' Add the the children to the married daughters
Set Mamy1.Children = New Collection
Mamy1.Children.Add Child_1a
Mamy1.Children.Add Child_1b

Set Mamy2.Children = New Collection
Mamy2.Children.Add Child_2a

' Create Grandmother
Dim GrandMa As GrandMother: Set GrandMa = New GrandMother
Set GrandMa.MarriedDaughter = New Collection
GrandMa.MarriedDaughter.Add Mamy1
GrandMa.MarriedDaughter.Add Mamy2

' Now cycle childs Name and debug:
Dim aChild As New Child
For Each aChild In GrandMa.MarriedDaughter.Children
 Debug.Print GrandMa.MarriedDaughter.Children.Name
Next aChild

End Sub

1 个答案:

答案 0 :(得分:1)

在两种情况下都发生该错误,您需要使用Set关键字来处理对象。那只是针对您评论的错误类型。

例如

Set Children = pChildren
Set MarriedDaughter = pMarriedDaughter

以下GrandMa.MarriedDaughter不会公开.Children顺便说一句。

也许

Dim aChild As MarriedMom, nextChild As Child   
For Each aChild In GrandMa.MarriedDaughter
    For Each nextChild In aChild.Children
        Debug.Print nextChild.Name
    Next
Next aChild