【问题标题】:call an object of a collection vba调用集合vba的对象
【发布时间】:2016-07-19 17:05:42
【问题描述】:

我有一个员工(对象)的集合,每个员工都有他/她自己的属性(属性),例如 ID、年龄等。 我已经定义了一个类模块(名为 clsemployee),如下所示:

公共 ID 为整数 公共年龄为整数 . .

并且我在一个模块中将 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

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

【问题讨论】:

  • 要全局访问变量,您可以在标准模块中将其声明为全局/公共。

标签: vba class object collections call


【解决方案1】:

扩展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 以获得对此的详细解释。

【讨论】:

  • 它给了我运行时错误 '424'" Object required 。似乎还没有定义集合。你试过代码吗?
  • 我已经尝试过了(尽管我删除了你的其余代码)。您是否删除了employee_collection 子例程中的“Dim employee as Collection”行?
  • employee.count 没问题,但我正在寻找诸如employee.ID 和employee.Age 之类的属性。
  • 好的,我看到它可以用 Debug.Print employee.Item(100).Age 调用。
  • Debug.Print 仅将值输出到即时窗口。我只是用它来展示如何访问该集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2012-08-26
  • 2016-06-09
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
相关资源
最近更新 更多