gpt4 book ai didi

VBA - 如何将集合添加到集合的集合中

转载 作者:行者123 更新时间:2023-12-01 18:37:58 28 4
gpt4 key购买 nike

我正在尝试在 Word 2007 中使用 VBA 创建代码来表示表单文档。我已经创建了类来表示部分、问题集和问题。

所以我有 15 个部分。我创建了一个函数来创建每个“Section”对象,将其添加到“Sections”集合中,然后销毁该对象,结果是对象在集合(或其他内容)中保持持久状态。

是否可以使用相同的方法将集合添加到集合中,或者我是否必须显式定义每个集合?

模块中的代码:

Public Sections As Collection

Function DefineSection(ByVal SectionName As String)

Set Section = New clsSection
Section.myName = SectionName
Sections.Add Section, SectionName

End Function


Function DefineQuestionSet(ByVal SectionName As String, ByVal Name As String, ByVal NoOfQuestions As Integer, ByVal IsMutuallyExclusive As Boolean, Optional ByVal DependentOnSection As String)

Dim Qsets As Collection

Set Qsets = New Collection
Set QuestionSet = New clsQuestionSet

QuestionSet.Name = Name
QuestionSet.NoOfQuestions = NoOfQuestions
QuestionSet.MutuallyExclusive = IsMutuallyExclusive

If Not (DependentOnSection) = "" Then
QuestionSet.DependentOnSection = DependentOnSection
End If

Qsets.Add QuestionSet
Sections.Item(SectionName).Add Qsets

End Function

然后通过以下方式调用:

Sub Initilise()

Set Sections = New Collection

DefineSection "PersonalDetails"
DefineQuestionSet "PersonalDetails", "PersonalDetails", 29, False

End Sub

最佳答案

。您绝对可以无限地添加集合到集合到集合。您发布的代码看起来只需浏览一下就应该可以工作。您有具体问题吗?

更新:VBA 仅传递对对象的引用 如果您在将对象分配给集合后显式销毁该对象(例如 Set myObj = Nothing ),那么您也将销毁集合内的对象。

[编辑]:显然这不是真的。来自 this website (首先由 Stevo 在评论中链接):

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

  • 创建该类的实例
  • 设置类的属性和方法
  • 将类添加到公共(public)集合
  • 卸载类的实例

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.

更新:没有理由不能将集合添加到对象中。您只需要实例化对象的类即可支持此类方法。例如,在您的clsSection中类模块,你需要一个 Add方法,将传递给它的对象添加到存储在 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

关于VBA - 如何将集合添加到集合的集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5116460/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com