Ste*_*evo 11 collections excel vba excel-vba word-vba
我正在尝试使用Word 2007中的VBA创建代表表单文档的代码.我创建了表示Section,QuestionSet和Question的类.
所以我有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
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式调用:
Sub Initilise()
Set Sections = New Collection
DefineSection "PersonalDetails"
DefineQuestionSet "PersonalDetails", "PersonalDetails", 29, False
End Sub
Run Code Online (Sandbox Code Playgroud)
是的.您绝对可以无限制地将集合添加到集合中.您发布的代码看起来应该只是通过浏览它来工作.你有特定的问题吗?
更新:VBA仅传递对象的引用. 如果在将对象分配给集合(例如,Set myObj = Nothing)之后显式销毁该对象,那么您还将销毁集合中的对象.
[编辑]:显然这不是真的.从这个网站(在评论中首先由Stevo链接):
要使用集合来管理类对象,必须执行以下操作:
您可能希望卸载类的实例会导致类被关闭和终止.但是,类对象仍然存在,因为您将它添加到集合,然后该集合拥有对该类的引用.这是一种非常强大的技术,允许您通过集合控制对象引用; 在从集合中删除它之前,类对象不会终止.
更新:没有理由不能为对象添加集合.您只需要实例化对象的类来支持这样的方法.例如,在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
Run Code Online (Sandbox Code Playgroud)