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

后端 未结 3 2024
礼貌的吻别
礼貌的吻别 2021-02-20 06:20

I am trying to create code to represent a form document using VBA in Word 2007. I have created classes to represent Section, QuestionSet and Question.

So I have 15 Secti

3条回答
  •  鱼传尺愫
    2021-02-20 06:58

    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
    

提交回复
热议问题