Lets say I have a custom collection and a custom object that have a Parent-Child relationship
I have a userform where the user names the collection and provides input for other properties of the collection. When they click “Add Parent” the click event is handled and calls the following function:
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
The user then sees a new form for creating a Child object. When the user clicks “Add Child” the event is handled and calls the following 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 parent collection'
newParent.Add newChild
End Function
And then the user needs to be able to return to the userform and add another child.
The lines that won’t work are:
newChild.xSlope = newParent.Xslope
and:
newParent.Add newChild
I get an ‘object required’ error.
How do I/where do I add the child to the Parent Collection?
First of all,
newParentis local to theAddParentfunction soAddChildhas no visibility of it. To fix that, you would need to moveDim newParent As clsParentout of theAddParentfunction and make it a module-level variable. This assumes thatAddParentandAddChildare in the same module.Secondly,
newParent.Add newChildwill only work if you have written anAddmethod inclsParent. If you have not then you’ll need to write one. I have no idea how you plan on using it, but the following code is pretty generic and should get you pointed in the right direction. This code would go in theclsParentmodule:This would build a private collection of
clsChildobjects that you would manipulate using additional methods or expose viaProperty Get.UPDATE: To address your comment, if you want to keep multiple parents you’ll need to add a collection for that. For example:
Of course, now you have another collection to keep track of. It gets really tricky keeping track of multiple instances of forms (which I assume is what you are doing) and it is easy to suddenly find yourself with an unmanageable mess.