VBA | 如何创build一个构build对象并将其分配给数组/集合的类模块
我对编码有点新,可能不会使用正确的术语,希望我说的是合理的。
我创build了一个类模块来构build对象。 我的类模块目前有一些variables(我打算添加一些方法,因为我build立在我的代码)。
'CLASS MODULE NAMED clsNodes Public i As Single Public j As Single Public coll As Collection
我的模块将build立基于用户input的单元格值的对象
Option Explicit Dim i As Single, j As Single Dim ni_nodes As Single, nj_anchors As Single ni_nodes = range("A1") nj_nodes = range("A2") For i = 1 to ni_nodes For j = 1 to nj_nodes Set node = New clsNodes node.i = i node.j = j Next j Next i
我的代码目前的问题是,当它通过我的for循环时,对象节点被覆盖的每一步它通过j for循环。
我想要做的是创build一个新的对象或添加对象到一个集合,所以我可以很容易地引用对象及其variables。 例如在我的模块,我想调用我的节点类似于…
1stnode_i_value = node(1).i 3rdnode_j_value = node(3).j
希望这是有道理的……我可能不会用最好的方法,所以请启发我。
您可以将对象存储在一个集合中:
Sub Test() Dim Node As clsNodes, i As Long, j As Long Dim coll As New Collection, n For i = 1 To 5 For j = 1 To 5 Set Node = New clsNodes Node.i = i Node.j = j coll.Add Node Next j Next i 'list out stored objects For Each n In coll Debug.Print ni, nj Next n End Sub
集合只能用String
值键入。 你可以将一个对象实例作为一个项目存储在一个集合中,但是集合有许多缺点,所以为了更好的select,比如数组或者字典。
既然我们想保持这个简单,我会去一个数组。 你的类的实例被覆盖,因为你没有保存它。 要保存所有的类实例,你可以这样做:
Option Explicit Dim i As Single, j As Single Dim ni_nodes As Single, nj_anchors As Single dim arr() as variant dim cnt as integer ni_nodes = range("A1") nj_nodes = range("A2") redim arr(1 to ni_nodes*nj_nodes) cnt=0 For i = 1 to ni_nodes For j = 1 to nj_nodes Set node = New clsNodes node.i = i node.j = j cnt=cnt+1 set arr(cnt)=node Next j Next i
从数组中检索你的对象,你应该这样做:
dim obj as object set obj=arr(i) 'i is the index you want
要么:
dim obj as clsNode set obj=new clsNode set obj=arr(i)