VBA |如何创建用于构建对象并将其分配给数组/集合的类模块 [英] VBA | How to create a class module which builds objects and assigns them to an array/collection

查看:228
本文介绍了VBA |如何创建用于构建对象并将其分配给数组/集合的类模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编码有些陌生,可能不会使用正确的术语,希望我所说的有意义。

I am somewhat new to coding and may not use the correct terminology, hopefully, what I say makes sense.

我创建了一个用于构建对象的类模块。我的类模块当前有一些变量(我打算在代码上构建一些方法)。

I have created a class module to build objects. My class module currently has some variables (I intend to add some methods as I build upon my code).

'CLASS MODULE NAMED clsNodes

Public i As Single
Public j As Single
Public coll As Collection

我的模块将根据用户输入的单元格值构建对象

My module will build objects based on cell value input by the user

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循环的每一步都会被覆盖。

The current problem with my code is that when it steps through my for loop the object node is overwritten every step it runs through the j for loop.

我做什么要做的是创建一个新对象或将该对象添加到collecti这样我就可以轻松引用该对象及其变量。例如,在我的模块中,我想调用类似于...的节点。

What I want to do is create a new object or add the object to a collection so I can easily reference the object and its variables. For example in my module I would like to call up my nodes similar to...

1stnode_i_value = node(1).i
3rdnode_j_value = node(3).j

希望这有道理...我

Hopefully, this makes sense... I may not be using the best approach so please enlightened me.

推荐答案

集合只能用 String 值。您可以将对象实例作为 存储在集合中,但是集合具有许多缺点,因此请选择更好的选择,例如数组或字典。

A collection can only be keyed with a String value. You can store an object instance as an item in a collection, but collections come with many shortcomings so go for better options, like an array or a dictionary.

由于我们要保持简单,因此我将使用数组。您的类实例被覆盖,因为您没有保存它。要保存所有类实例,可以执行以下操作:

Since we want to keep this simple, I would go with an array. Your instance of the class is overwritten because you are not saving it. To save all of your class instances you can do this:

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

要从数组中检索对象,您应该执行以下操作:

to retrieve your objects from the array you should do this:

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)

这篇关于VBA |如何创建用于构建对象并将其分配给数组/集合的类模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆