【问题标题】:Why won't VBA array with in ArrayList ReDim inside a subrotine and preserve the scope?为什么 VBA 数组不能在子程序内的 ArrayList ReDim 中保留范围?
【发布时间】:2021-06-23 17:08:01
【问题描述】:

我正在使用 ReDim 在单独的子例程中更改数组列表中数组的大小。但是主子程序中的数组大小没有改变。我正在使用 ByRef。 findItem 检查一个数组中的任何项目是否存在于另一个数组中。控制台中的打印输出是

In Change Array Size: 12
In combine Array Size: 6
In Change Array Size: 14
In combine Array Size: 7

这是我的代码

Sub combineCRMITN(ByRef assocMap As Object, TN As Object, crmitnAbort As Date)
    Dim assocRow As Long, tnRow As Variant, assocSize As Long, TnStrCount As Long, assocSizeNew As Long, wholeSize As Long
    For assocRow = 0 To assocMap.Count - 1
        For Each tnRow In TN
            If findItem(assocMap.Item(assocRow), tnRow) Then
                TnStrCount = CountString(tnRow)
                assocSize = UBound(assocMap.Item(assocRow))
                Call changeSize(assocMap.Item(assocRow), assocSize)
                Debug.Print ("In combine Array Size: " & UBound(assocMap.Item(assocRow)))
                Exit For
            End If
        Next tnRow
        If Now > crmitnAbort Then Exit For
    Next assocRow
End Sub

Sub changeSize(ByRef theArray As Variant, newArrSize As Long)
    Dim theArraySize As Long
    theArraySize = UBound(theArray)
    ReDim theArray(theArraySize + newArrSize)
    Debug.Print ("In Change Array Size: " & UBound(theArray))
End Sub

Function findItem(arrRow1 As Variant, arrRow2 As Variant) As Boolean
    Dim arr1Size As Long, arr1ind As Long
    arr1Size = UBound(arrRow1)
    For arr1ind = 0 To arr1Size
        If IsIn(VarType(arrRow1(arr1ind)), "2,3,4,5") Then
            If IsInArray(CLng(arrRow1(arr1ind)), arrRow2) Then
                findItem = True
                Exit Function
            End If
        End If
    Next arr1ind
    findItem = False
End Function

最终结果是在主函数 combineCRMITN 中数组大小会发生变化。

【问题讨论】:

    标签: arrays vba


    【解决方案1】:

    如果 assocMap 是脚本字典,则不能修改存储在其中的数组:必须先将数组提取到变量中,然后修改它,然后替换它。

    Dim tmp
    '...
    '...
    tmp = assocMap.Item(assocRow)
    changeSize tmp, assocSize
    assocMap.Item(assocRow) = tmp
    

    存储在集合中的数组也是如此。例如:

    Dim col As New Collection
    
    col.Add Array(1)
    
    Debug.Print col(1)(0) '1
    
    col(1)(0) = 2
    
    Debug.Print col(1)(0) 'still 1
    

    以前:Changing array values in a VBA dictionary

    编辑——刚刚注意到标题中的 ArrayList:同样如此......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 2012-11-16
      • 2023-03-28
      相关资源
      最近更新 更多