VBA - How to add a collection to a collection of collections

只愿长相守 提交于 2019-12-05 01:10:39

Yes. You can absolutely add collections to collections to collections ad infinitum. The code you have posted looks like it should work just from glancing through it. Are you having specific problems?

UPDATE: VBA only passes around references to objects. If you explicitly destroy an object after assigning it to a collection (eg, Set myObj = Nothing) then you will also be destroying the object inside the collection.

[EDIT]: Apparently this is not true. From this website (first linked by Stevo in the comments):

In order to use collections to manage class objects, you must do the following:

  • Create an instance of the class
  • Set the properties and methods of the class
  • Add the class to a public collection
  • Unload the instance of the class

You might expect that unloading the instance of the class results in the class being closed and terminated. However, the class object persists because you add it to a collection, which then owns the reference to the class. This is a very powerful technique that allows you to control object references through a collection; the class object does not terminate until you remove it from the collection.

UPDATE: There's no reason why you can't add a collection to an object. You just need the class your object is instantiated from to support such a method. For example, in your clsSection class module you need an Add method which adds objects passed to it to a collection stored in the clsSection:

Private QSetsColl As Collection

Public Sub Add(QSets As Object)
    If QSetsColl Is Nothing Then Set QSetsColl = New Collection
    QSetsColl.Add QSets
End Sub

Try this simple example:

Private Sub CommandButton1_Click()

    Dim masterCollection As New collection
    masterCollection.Add "first key", createDetailCollection()
    masterCollection.Add "second key", createDetailCollection()
    masterCollection.Add "third key", createDetailCollection()

End Sub

The follow function return a initializated collection

Function createDetailCollection()
    Dim collection As New collection
    createCollection = collezioneBuy
End Function

I think I have the answer now, but if someone could clarify that would be helpful.

I think what the code is doing is trying to add a collection to an object - which obviously won't work. So I need to create a collection which I can add the object AND the collection to. etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!