使用ReDim(VBA)超出范围的下标

时间:2020-12-13 16:42:57

Could you please explain to me why this simple VBA code fails at the last line ("Subscript out of Range"):

你可以向我解释为什么这个简单的VBA代码在最后一行失败(“下标超出范围”):

    Dim test() As Variant
    ReDim test(0, 1)
    test(0,0) = "key"
    test(0,1) = 1
    ReDim Preserve test(1, 1)

1 个解决方案

#1


15  

Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array, and for every other dimension you must specify the same bound it already has in the existing array.

使用Preserve调整大小。如果使用“保留”,则只能调整数组的最后一个维度,对于每个其他维度,必须指定现有数组中已有的相同边界。

For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension if you use Preserve.

例如,如果您的数组只有一个维度,则可以调整该维度的大小并保留数组的所有内容,因为您要更改最后一个维度。但是,如果您的数组有两个或更多维度,则可以在使用“保留”时更改最后一个维度的大小。

#1


15  

Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array, and for every other dimension you must specify the same bound it already has in the existing array.

使用Preserve调整大小。如果使用“保留”,则只能调整数组的最后一个维度,对于每个其他维度,必须指定现有数组中已有的相同边界。

For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension if you use Preserve.

例如,如果您的数组只有一个维度,则可以调整该维度的大小并保留数组的所有内容,因为您要更改最后一个维度。但是,如果您的数组有两个或更多维度,则可以在使用“保留”时更改最后一个维度的大小。