BaseClass中subClass的集合

时间:2017-11-18 08:23:53

标签: vba

我想创建以下结构: enter image description here

我创建了以下代码:

使用命令按钮进行Userform(用于激活代码)

Option Explicit

Public myCollection As Collection

Private Sub CommandButton1_Click()
    Dim subItem As SubClass
    Dim baseItem As BaseClass

    Set baseItem = New BaseClass
    Set subItem = New SubClass

    subItem.itemName = "Something"

    baseItem.addSubItem (subItem)    <---- ERROR ON THIS ROW!

    myCollection.Add (baseItem)
End Sub

Private Sub UserForm_Initialize()
    Set myCollection = New Collection
End Sub

BaseClass的

Option Explicit

Private subClassCollection As Collection

Public Sub addSubItem(subItem As SubClass)
    Call subClassCollection.Add(subItem, Key:=subItem.itemName)
End Sub

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

子类

Option Explicit

Private sItemName As String

Property Get itemName() As String
    itemName = sItemName
End Property

Property Let itemName(name As String)
    sItemName = name
End Property

当我运行此代码时,我在Userform中突出显示的行上收到以下错误“对象不支持此属性或方法”。

我认为这个例子很简单..我错过了什么?

1 个答案:

答案 0 :(得分:2)

调用子例程/方法时,不应在括号周围放置括号。括号强制VBA尝试并评估表达式(subItem)(例如),它无法做到。

应运行以下主要代码。 (不能保证它正在做正确的事情,但它至少不会崩溃。)

Option Explicit

Public myCollection As Collection

Private Sub CommandButton1_Click()
    Dim subItem As SubClass
    Dim baseItem As BaseClass

    Set baseItem = New BaseClass
    Set subItem = New SubClass

    subItem.itemName = "Something"

    baseItem.addSubItem subItem

    myCollection.Add baseItem
End Sub

Private Sub UserForm_Initialize()
    Set myCollection = New Collection
End Sub

调用过程等的语法类似于:

procedure parm1, parm2, parm3

或(过时的版本)

Call procedure(parm1, parm2, parm3)

或(使用函数)

returnValue = procedure(parm1, parm2, parm3)