首先,如果我使用了不正确的术语,请原谅我对我的问题的解释,我没有经验和自学成才。
我正在学习使用类模块来设置“对象”以更轻松地引用变量并运行常用函数。我遇到的问题是我找不到有关如何设置可以充当集合以利用集合中固有的添加功能的类模块的信息。
例如,我有一个名为 clsSchool 的父类模块
在这个类模块中,我定义了一个对象,以便我可以设置一个“子”类 clsTeacher
在我的 clsTeacher 类模块中,我设置了一个字符串变量名称。这就是我的 2 类模块的外观。
cls学校
Public Student As Object
cls老师
Public Name as String
在我的模块中,我有
现代学校
Set mySchool = New clsSchool
Set mySchool.Teacher = New clsTeacher
mySchool.Teacher.Name = "Jim"
此时,我的代码正是我想要的,使用变量 mySchool.Teacher.Name 来调用“Jim”非常容易,我还可以使用带有 mySchool.Teacher 的 while 循环来调用我在我的定义中定义的各种变量cls老师
我的问题是我想添加多名教师,而不必在我的代码顶部设置多个类(class),因为教师的数量可能会有所不同。 IE。以下确实有效,但有局限性。
现代学校
Set mySchool = New clsSchool
Set mySchool.Teacher1 = New clsTeacher
Set mySchool.Teacher2 = New clsTeacher
Set mySchool.Teacher3 = New clsTeacher
mySchool.Teacher1.Name = "Jim"
mySchool.Teacher2.Name = "Jack"
mySchool.Teacher3.Name = "John"
我想要的是类似于集合如何工作的东西。 IE。我想找到教师的总数(会有所不同)并创建一个 for 循环来为每个唯一的教师创建一个新的 clsTeacher。我想要的是类似于以下内容,但我被卡住了,我找不到任何有助于解释如何设置以下内容的资源。
现代学校
Set mySchool.Teacher = New clsTeacher
n_teachers = 6
for i=1 to n_teachers
mySchool.Teacher(i).Name = Range("A1").Offset(i,0)
Next i
这样我可以很容易地记忆起老师 1 或老师 2 的名字,并使用 while/for 循环来做到这一点。
最佳答案
您可以创建一个隐藏 clsTeachers
集合的类 ( clsTeacher
) s。下面是一些可以做的事情的示例 - 有效地添加到 Collection 可以做的事情。
Private pTeachers as New Collection ' Debate: New in the declaration, or New in Class_Initialise?
Property Get Count() as Long
Count = pTeachers
End Property
Sub AddTeacher(NewTeacher as clsTeacher) ' enforces type.
pTeachers.Add(NewTeacher)
End Sub
Function SortTeachers1() as clsTeachers
Dim tNewTColl as clsTeachers
'some sort routine using the existing collection and adding in order to a new class
Set SortTeachers = tNewColl
End Function
Sub SortTeachers2()
Dim tNewColl as New Collection
'some sort routine using the existing collection and the new one
Set pTeachers = tNewColl
End Sub
Sub PrintTeachers()
Dim tTchr as clsTeacher
For each tTchr in pTeachers
'valid print command or add to string for later printing
Next 'tTchr
End Sub
这些方法仅受您的想象力限制。我发现的一个缺点是在“For Each”循环中使用它并不容易。标准
For I = 1 to MyTeachers.Count
是一个有用的后备 - 只是不那么整洁。在类里面,您可以:Property Get Teacher(Index as Long) as clsTeacher
'error check here to ensure Index exists
if tIndexValid then
Teacher = pTeachers(Index)
else
Teacher = Nothing 'or however you want to handle this
end if
End Property
我发现这种收集集合的方式很有用,因为您可以在主代码 View 中隐藏验证和定制输出。正如您从签名中看到的那样,您还可以强制类型(即您选择的集合中只能包含教师)。
** 使用自定义集合进行 for-each 的一些引用:
其中包括其他链接。
关于vba - 如何使用类模块来设置父变量和子变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48415025/