对象的集合在通过数组循环时将新UDT传递给每个对象

时间:2017-11-03 01:14:55

标签: excel excel-vba object collections user-defined-types vba

我的aMRecon数组是2500行x 65列。我需要在每一行中评估多达10列以上,因此我认为我需要创建一个代表每一行的对象。我创建了一个UDT,在下面的基本过程中,我尝试创建一个object for each row,每个对象都有一个.EntityID属性(这是{{1}中每行的单元格值}或Column B)。

Column 2

我是否需要以某种方式创建对象集合?有人可以给我一个例子来帮忙。截至目前,我认为我只有一个对象,Public Type BreakInfo EntityID As String IssueName As String ValDate As Date LedgerAMT As Long NetAMTL As Long PriceDiff As Long End Type Sub Fill_Objects() Dim aMrow As Integer, aMcol As Integer Dim BI As BreakInfo For aMcol = LBound(aMRecon, 2) To UBound(aMRecon, 2) For aMrow = LBound(aMRecon, 1) To UBound(aMRecon, 1) If aMcol = 2 Then Debug.Print aMRecon(aMrow, aMcol) Set ObjLSL = New Collection BI.EntityID = aMRecon(aMrow, aMcol) End If Next aMrow Next aMcol End If End Sub 属性不断被覆盖。谢谢

事实上,每一行只有1个属性,基本上每个属性都是一个列标题。我这是最有效的方式吗?最终,我需要评估一个对象中的每个属性并对其进行分类。

插入了ClassModule权限.EntityID

BreakInfo

这就是全班同学。

1 个答案:

答案 0 :(得分:1)

您需要首先创建(插入)一个类模块,将其命名为BreakInfo,并为其提供如下公共成员:

Option Explicit

Public EntityID As String
Public IssueName As String
Public ValDate As Date
Public LedgerAMT As Long
Public NetAMTL As Long
Public PriceDiff As Long

然后你可以使用这样的东西:

Sub Fill_Objects()
    Dim aMrow As Integer, aMcol As Integer
    Dim BI As BreakInfo
    Dim ObjLSL As Collection
    Dim key As Long

    'Create the Collection instance.
    Set ObjLSL = New Collection

    For aMcol = LBound(aMRecon, 2) To UBound(aMRecon, 2)
        For aMrow = LBound(aMRecon, 1) To UBound(aMRecon, 1)
            If aMcol = 2 Then
                'Instantiate a BreakInfo.
                Set BI = New BreakInfo
                BI.EntityID = aMRecon(aMrow, aMcol)
                '...

                key = key + 1
                ObjLSL.Add BI, CStr(key)
            End If
        Next aMrow
    Next aMcol
End Sub

请注意,集合在循环之前被实例化一次。集合不能摄取用户定义类型的变量,但它很乐意吞噬对象实例。

修改

问题已经改变。如果您担心效率问题,可以硬编码aMcol = 2,不要使用外部ForIf aMcol = 2。除此之外,我不明白你在尝试用自己的价值做些什么。