您可以使用变量创建对象吗?
我有一个包含多个名称的数组,对于每个名称,我想创建一个对象。
所以我有("Max", "Tim", "Fred")
并希望循环遍历该数组,结果是我得到类似于手动操作的内容,如此
Dim Max as CmyClass
Dim Tim as CmyClass
Dim Fred as CmyClass
(如果这非常违反编程的所有良好习惯,请告诉我如何正确地做到这一点)
由于
答案 0 :(得分:4)
据我所知,这并不反对良好的编程,但你需要一些东西来存储对象,在VBA的情况下,它将是一个数组或集合。
类似这样的事情
Sub test()
Dim col As Collection
Set col = New Collection
For i = 0 To 4
Dim Name As Class1
Set Name = New Class1
col.Add Name, "test" & i
Next i
End Sub
答案 1 :(得分:1)
Sub Tester()
Dim d As Object
Dim o As CmyClass
Dim arr, k, x
Set d = CreateObject("scripting.dictionary")
arr = Array("Max", "Tim", "Fred")
For x = LBound(arr) To UBound(arr)
Set o = New CmyClass
'set o properties etc
o.Name = "Name is " & arr(x)
d.Add arr(x), o
Next x
For Each k In d.keys
Debug.Print k, d(k).Name
Next k
End Sub