调用集合的对象 vba

call an object of a collection vba

我有一组员工(对象),每个员工都有 his/her 自己的属性(属性),例如 ID、年龄等。 我定义了一个 class 模块(名为 clsemployee),如下所示:

Public ID 为整数 Public 年龄为整数 . .

然后我在一个模块中添加了ID、年龄等属性到集合中,如下所示:

Public Sub employee_collection() ' this collection saves all of the employees records

Dim employee As Collection
Set employee = New Collection
Dim n As Integer
Dim i As Integer
Dim E1 As Variant
Dim j As Integer
n = 528

Dim a, b As String
For i = 3 To n
a = "A" + CStr(i) ' to get the values from the excel sheet
b = "B" + CStr(i)

Set E1 = New clsEmployee
E1.ID = Sheets("A").Range(a).Value ' save the valus of each employee in the collection
E1.Age = Sheets("A").Range(b).Value
employee.Add E1

Next i
End Sub

我不知道如何在我的其他模块(子)中调用这个集合。我应该按值调用还是按引用调用?我不想在我拥有的每个子系统中重复定义该员工。

扩展 cyboashu 所说的内容:

Global employee as Collection

Public Sub employee_collection()

     Set employee = New Collection
     ....'rest of code here

End Sub

Public Sub use_collection()

    Debug.print employee.count

End Sub

注意全局声明需要在模块中,也如cyboashu所述

运行 employee_collection 代码 1 次,当您想用员工填充集合时。然后,您可以在任何进一步的过程中简单地使用该集合,因为它已经被填充了。

请注意,可以重置全局变量。请参阅 here 以获得对此的详细解释。