2012-03-29 71 views
1

我有这样的代码:VBA:我改变了ARR(0),不明白为什么ARR(1)改变了?

Call MakeRoomForArrayItem(interAll, 0) 

interAll(0).StartY = tempStartY 
interAll(0).K = tempK 

在我被一个成功地创建一个新的细长interAll()的第一行。

然后我希望第二行和第三行仅影响interAll(0),但它们对interAll(1)执行相同的更改。为什么是这样?我没有成功创建interAll(1)的新对象吗?

Sub MakeRoomForArrayItem(ItemArray As Variant, ByVal ItemElement As Integer) 
    Dim i As Integer 
    ReDim Preserve ItemArray(LBound(ItemArray) To UBound(ItemArray) + 1) 

    For i = UBound(ItemArray) - 1 To ItemElement Step -1 
     Set ItemArray(i + 1) = ItemArray(i) 
    Next 
    'Erase values in object ItemArray(ItemElement) would be nice 
End Sub 

我在其他情况下成功地使用了相同的功能。它可能与调用函数中缺少声明有关吗?

编辑:我加入

Set interval = New CInterval 
Set interAll(0) = interval 

你能向我解释这里到底发生了什么,这样我就不会再犯同样的错误修复了这个问题?

+0

嘘,千万不要忘了给予好评,你发现的有用的意见,并接受你找到最有用的答案! (它不一定是我的!) – 2012-03-29 22:18:46

回答

1

这取决于你通过什么样的变量MakeRoomForArrayItem。如果阵列是持有值类型变量,如整型或布尔,那么它会工作,因为赋值语句

Set ItemArray(i + 1) = ItemArray(i) 

被复制的值。但是,如果您正在使用通过引用传递的变量,那么您并未复制其值,而是将引用复制到变量中。在这种情况下,您似乎传递了一个类变量,它将通过引用传递。

编辑:当你打电话到New CInterval,你实际上分配一个新的变量,而不是复制一个引用到以前的变量。这就是你的修复工作的原因。没有你的修复,你只有一个“槽”在内存中保存一个值,但你的数组多次引用该内存。修复之后,您在内存中拥有与调用New CInterval一样多的“插槽”,并且阵列的每个元素都引用新的内存位置。

也许下面的代码将有助于:

Set interval1 = New CInterval ' you have a single CInterval instance 
Set interval2 = New CInterval ' changes to interval1 or interval2 do not affect each other 
Set interval3 = interval2  ' changes to interval3 also make changes to interval2, 
           ' because they are the same object. 
Dim arr as CInterval(3)   
' Create a single array that has 3 elements, 
' which will hold 3 references to CInterval instances. 
' Those references may or may not be to the same actual CInterval instance. 

Set arr(0) = interval1 ' the first element of the array references the first object instance 
Set arr(1) = interval1 ' the second element of the array also references the first object instance 
Set arr(2) = interval2 ' the third element of the array references the second object instance. 
         ' Changes to this element will affect both interval2 and interval3, because they are references to the same object in memory. 
1

当你这样做:

Set ItemArray(i + 1) = ItemArray(i)

要复制引用,而不是值。因此,在循环结束时,当i=0时,该行说的是“将对象的引用复制到位置1的ItemArray(0)”。因此,ItemArray(0)ItemArray(1)都包含指向相同对象实例的引用。您应该能够使用调试器来确认这一点。

相关问题