vba 创建对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9686415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating a list of objects
提问by user1266138
Hi can I use a variable to create an object.
I have an array of several names and for each of those names, I would like to create an object.
So I have ("Max", "Tim", "Fred")
and would like to loop through that array with the result that I get something similar to doing it manual like this
嗨,我可以使用变量来创建对象吗?我有一个包含多个名称的数组,对于每个名称,我想创建一个对象。所以我已经("Max", "Tim", "Fred")
并且想要遍历该数组,结果我得到类似于这样做的手册
Dim Max as CmyClass
Dim Tim as CmyClass
Dim Fred as CmyClass
(if that is very much against all good habits of programming, please let me know how to do that properly)
(如果这与所有良好的编程习惯背道而驰,请告诉我如何正确地做到这一点)
Thanks
谢谢
回答by len
It's not against good programming for as far as I know, but you would need something to store the objects in, which in the case of VBA would be an array or a collection.
据我所知,这并不反对良好的编程,但是您需要一些东西来存储对象,在 VBA 的情况下,它是一个数组或一个集合。
something like this
像这样的东西
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
回答by Tim Williams
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