vba将动态数组传递给类

时间:2017-01-09 14:02:42

标签: vba

我有一个问题,动态数组传递给类byVal而不是byRef,所以简化类,cArray

Option Explicit

Private mArray() As String

Public Sub init(ByRef iArray() As String)
    mArray = iArray
End Sub

Public Property Get count() As Long
    count = UBound(mArray) - LBound(mArray)
End Property

Public Property Get item(iIndex As Long) As String
    item = mArray(iIndex)
End Property

和模块中的简单功能

Private Sub arrTest()
    Dim arr() As String, cont As cArray
    ReDim arr(0 To 1)

    arr(0) = "value0"
    arr(1) = "value1"

    Set cont = New cArray
    cont.init arr

    arr(1) = "newValue1"
    Debug.Print cont.item(1), arr(1) 'will print value1, newValue1 even though is expected to be same

    ReDim Preserve arr(0 To 2)
    arr(2) = "value2"

    Debug.Print cont.count 'will print 1
End Sub

所以,问题是,这个错误吗?正常的行为?别的什么?

1 个答案:

答案 0 :(得分:0)

实际上,数组通过引用传递。问题出现在分配上。

在VBA中将一个数组变量分配给另一个数组变量或将一个字符串变量分配给另一个字符串变量创建一个副本虽然有很多方法可以使用VariantsCopyMemory,例如。如果您有兴趣,请发表评论。

我可以通过使用VarPtr获取实际地址进行比较来证明这一点。我们在你的代码中加几行......

<强> CARRAY

Option Explicit

Private mArray() As String

Public Sub init(ByRef iArray() As String)
    Debug.Print "The address of the function parameter is: " & VarPtr(iArray(0)) '<----- add this line
    mArray = iArray
    Debug.Print "The address of the mArray class member is: " & VarPtr(mArray(0)) '<----- add this line
End Sub

Public Property Get count() As Long
    count = UBound(mArray) - LBound(mArray)
End Property

Public Property Get item(iIndex As Long) As String
    item = mArray(iIndex)
End Property

<强> mdlMain

Private Sub arrTest()
    Dim arr() As String, cont As cArray
    ReDim arr(0 To 1)

    arr(0) = "value0"
    arr(1) = "value1"

    Debug.Print "The address of the newly dimensioned and initialized arr is: " & VarPtr(arr(0)) '<----- add this line

    Set cont = New cArray
    cont.init arr

    arr(1) = "newValue1"

    Debug.Print cont.item(1), arr(1) 'will print value1, newValue1 even though is expected to be same

    ReDim Preserve arr(0 To 2)
    arr(2) = "value2"

    Debug.Print cont.count 'will print 1
End Sub

当我运行时,我得到(内存地址可能会有所不同):

The address of the newly dimensioned and initialized arr is: 192524056
The address of the function parameter is: 192524056 The address of the
mArray class member is: 192524040 
value1        newValue1  1

所以你可以看到实际的函数参数 WAS 通过引用传递,但是赋值创建了一个副本。