尝试使用示例设置自定义对象模型,但不工作

我试图设置一个自定义的对象模型使用我在一个回答问题在这里find一个例子在stackoverflow。

VBA类 – 如何让一个类拥有额外的类

这是我根据答案创build的代码。

标准模块

Sub test() Dim i As Long Dim j As Long 'code to populate some objects Dim AssemList As Collection Dim Assem As cAssem Dim SubAssemList As Collection Dim SubAssem As cSubAssem Set AssemList = New Collection For i = 1 To 3 Set SubAssemList = New Collection Set Assem = New cAssem Assem.Description = "Assem " & i For j = 1 To 3 Set SubAssem = New cSubAssem SubAssem.Name = "SubAssem" & j SubAssemList.Add SubAssem Next j Set Assem.SubAssemAdd = SubAssemList '<------ Object variable or With Block not Set AssemList.Add Assem Next i Set SubAssemList = Nothing 'write the data backout again For Each clock In AssemList Debug.Print Assem.Description Set SubAssemList = Assem.SubAssems For Each SubAssem In SubAssemList Debug.Print SubAssem.Name Next Next End Sub 

cAssem类

 Private pDescription As String Private pSubAssemList As Collection Private Sub Class_Initialize() Set pSubAssems = New Collection End Sub Public Property Get Description() As String Description = pDescription End Property Public Property Let Description(ByVal sDescription As String) pDescription = sDescription End Property Public Property Get SubAssems() As Collection Set SubAssems = pSubAssemList End Property Public Property Set SubAssemAdd(AssemCollection As Collection) For Each AssemName In AssemCollection pSubAssemList.Add AssemName ' <------- This is the line that is triggering the error Next End Property 

cSubAssem类

 Private pSubAssemName As String Public Property Get Name() As String Name = pSubAssemName End Property Public Property Let Name(ByVal sName As String) pSubAssemName = sName End Property 

除了类名和variables名之外,我没有改变代码中的任何东西,从我的有限观点来看,我无法理解错误的原因。

我刚开始深入挖掘VBA中的对象和类模块,所以我很欣赏这个社区可以通过我的方式。

非常感谢

你的子类初始化器中有一个错字:

 Private Sub Class_Initialize() Set pSubAssems = New Collection End Sub 

应该读:

 Private Sub Class_Initialize() Set pSubAssemList = New Collection End Sub