ReDim保留二维变量数组

时间:2019-03-21 13:21:34

标签: arrays excel vba

这似乎是这个主题的第百万个问题,但是搜索并没有帮助我。

我正在尝试调整二维数组的最后一个维度的大小,但是在ReDim Preserve行中总是出现“索引越界”错误。

enter image description here

Dim arrCurrentDataset As Variant

For i = 0 To UBound(fileNames) - 1

    strPath = fileNames(i)

    Set wkbSource = Workbooks.Open(Filename:=strPath, UpdateLinks:=xlUpdateLinksNever, ReadOnly:=True, Notify:=True)
    Set wksSource = wkbSource.Sheets(1)

    Dim lngRows As Long
    lngRows = wksSource.UsedRange.SpecialCells(xlCellTypeLastCell).Row

    'Store dataset to array and afterwards increase second dimension by 2 -> create space to add Materialart and Beschaffungsart
    arrCurrentDataset = wksSource.Range("A4:I" & lngRows).value
    ReDim Preserve arrCurrentDataset(UBound(arrCurrentDataset, 1), UBound(arrCurrentDataset, 2) + 2)

    '...

next i

我的声明有问题吗?我是否隐式尝试更改数据类型?

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您的数组维数基于1,但是默认值是0(除非您有Option Base 1语句),因此必须在Redim中指定:

ReDim Preserve arrCurrentDataset(1 to UBound(arrCurrentDataset, 1), 1 to UBound(arrCurrentDataset, 2) + 2)

答案 1 :(得分:0)

当您将变量声明为Variant时,它可以是任何东西。它可以是数组,也可以是二维数组,但也可以是对象,字符串或其他东西。

因此,当您希望它成为数组时,必须使用Redim命令。但是,当您第一次点击Redim时,您还没有数组,因此Ubound将会失败(仅对数组有效)-并且因为它不是数组,所以也有什么都没保留。

您可以通过在实际工作开始之前初始化数组或添加检查变量是否包含数组来解决此问题

If isArray(arrCurrentDataset) Then
   ReDim Preserve arrCurrentDataset(1 to UBound(arrCurrentDataset, 1), 1 to UBound(arrCurrentDataset, 2) + 2)
Else
   ' You have to make up your mind about the initial size of the array
   ReDim arrCurrentDataset(1 to 10, 1 to 10)
End If
相关问题