需要帮助将自定义对象添加到自定义集合

时间:2011-02-17 20:17:12

标签: vba excel-vba excel

假设我有一个自定义集合和一个具有父子关系的自定义对象

我有一个userform,其中用户为集合命名,并为集合的其他属性提供输入。单击“添加父项”时,将处理单击事件并调用以下函数:

Public Function AddParent()

    Dim newParent As clsParent

    Set newParent = New clsParent

    'Add Parent Properties'

        With frmAddParent
            newParent.Name = .cboParentName.Value
            newParent.Width = .txtParentWidth.Value
            newParent.Xslope = .txtParentCrossSlope.Value
        End With

    'show the form for creating the Child Object'

    frmAddLaneMaterial.Show

End Function

然后,用户会看到一个用于创建Child对象的新表单。当用户单击“添加子项”时,将处理事件并调用以下函数:

Public Function AddChild()

    Dim newChild As clsChild
    Set newChild = New clsChild

        'Add child Properties'

        With frmAddChild

            newChild.Name = .cboParentName.Value
            newChild.LayerNumber = .cboLayerNum.Value
            newChild.xSlope = newParent.Xslope

        End With

    'Add the new child to the parent collection'

    newParent.Add newChild

End Function 

然后用户需要能够返回到用户表单并添加另一个孩子。

不起作用的行是:

            newChild.xSlope = newParent.Xslope

newParent.Add newChild

我收到'需要对象'错误。

我如何/在哪里将孩子添加到父集合?

1 个答案:

答案 0 :(得分:1)

首先,newParentAddParent函数的本地,因此AddChild无法看到它。要解决此问题,您需要将Dim newParent As clsParent移出AddParent函数并使其成为模块级变量。这假定AddParentAddChild位于同一模块中。

其次,newParent.Add newChild只有在Add中编写clsParent方法时才有效。如果你还没有,那么你需要写一个。我不知道您打算如何使用它,但以下代码非常通用,应该让您指向正确的方向。此代码将放在clsParent模块中:

Private m_oChildren As Collection

Sub Add(Child As clsChild)
    If m_oChildren Is Nothing Then Set m_oChildren = New Collection
    m_oChildren.Add Child
End Sub

这将构建一个clsChild个对象的私有集合,您可以使用其他方法操作或通过Property Get公开。

更新:要解决您的评论,如果您想保留多个父母,则需要为此添加一个集合。例如:

Dim Parents As Collection

Public Function AddParent()
Dim newParent As clsParent
    Set newParent = New clsParent

    'Add Parent Properties'
    With frmAddParent
        newParent.Name = .cboParentName.Value
        newParent.Width = .txtParentWidth.Value
        newParent.Xslope = .txtParentCrossSlope.Value
    End With

    'Initialize the collection of Parents if it has not already been done'
    If Parents Is Nothing Then Set Parents = New Collection
    'Add the new parent object to the Parents collection'
    Parents.Add newParent

    'show the form for creating the Child Object'
    frmAddLaneMaterial.Show
End Function


Public Function AddChild()
Dim newChild As clsChild
    Set newChild = New clsChild

    'Add child Properties'
    With frmAddChild
        newChild.Name = .cboParentName.Value
        newChild.LayerNumber = .cboLayerNum.Value
        newChild.xSlope = newParent.Xslope
    End With

    'Add the new child to the most recently added parent in the parent collection'
    Parents.Item(Parents.Count).Add newChild

End Function

当然,现在你有另一个集合来跟踪。跟踪多个表单实例(我假设你正在做的事情)变得非常棘手,并且很容易突然发现自己陷入无法控制的混乱状态。