添加对象后,将覆盖原始对象的数组

时间:2012-04-02 01:23:15

标签: vba excel-vba excel

我有一个方法是在循环中向数组添加自定义对象。问题是,添加到数组的最后一个对象似乎覆盖了数组中的所有其他对象。我已经通过代码看到最初添加了正确的对象,但我似乎无法弄清楚为什么最后一个对象会覆盖所有其他对象。我觉得它与内存指针和我的CallNum对象有关,但我无法弄清楚这一点。

Function getCallNumObjects(TotalCol As Integer) As Lib_CallNum
'
'   Find all the call numbers and their coresponding total
'
    Dim CallNumObjs() As Lib_CallNum
    Dim i As Integer

    i = 0
    Do Until ActiveCell.Value = "$<total:U>"
        If i <> 1 Or i <> 0 Then
            ReDim Preserve CallNumObjs(i) As Lib_CallNum
        End If
        Dim CallNum As New Lib_CallNum
        CallNum.Title = Replace(ActiveCell.Value & ActiveCell.Offset(1, 0).Value, " ", "")
        CallNum.Total = ActiveCell.Offset(0, TotalCol - 1).Value
        Set CallNumObjs(i) = CallNum
        ActiveCell.Offset(2, 0).Activate
        Debug.Print CallNumObjs(i).Title
        i = i + 1
    Loop

    Debug.Print CallNumObjs(0).Title
    Debug.Print CallNumObjs(1).Title
    Debug.Print CallNumObjs(2).Title



    Set getCallNumObjects = CallNumObjs
End Function

此功能的输出为:

DS0000701-DS000800

LH-PK

PL001001-PL003300

循环后的打印件为:

PL001001-PL003300

PL001001-PL003300

PL001001-PL003300

1 个答案:

答案 0 :(得分:1)

CallNumObjs是一个Lib_CallNum数组。该函数将该数组分配给Lib_CallNum的单个实例,而不是数组。也许如果你的功能被定义为:

Function getCallNumObjects(TotalCol As Integer) As Lib_CallNum()

编辑:我将注释中的更改合并,并删除了中间的CallNum变量。这至少可以清除不需要的东西进行调试。此外,我认为该变量的重复实例化可能会导致您的问题:

Function getCallNumObjects(TotalCol As Integer) As Lib_CallNum ()
    Dim CallNumObjs() As Lib_CallNum
    Dim i As Integer

    i = 0
    Do Until ActiveCell.Value = "$<total:U>"
        ReDim Preserve CallNumObjs(i) As Lib_CallNum
        CallNumObjs(i).Title = Replace(ActiveCell.Value & ActiveCell.Offset(1, 0).Value, " ", "") = CallNum
        CallNumObjs(i).Total = ActiveCell.Offset(0, TotalCol - 1).Value
        ActiveCell.Offset(2, 0).Activate
        i = i + 1
    Loop
    Set getCallNumObjects = CallNumObjs
End Function