ReDim (VBA) 下标超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7847284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:19:35  来源:igfitidea点击:

Subscript out of Range with ReDim (VBA)

arraysvba

提问by reggie

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)

回答by Emir Akayd?n

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.

例如,如果您的数组只有一个维度,您可以调整该维度的大小并仍然保留数组的所有内容,因为您正在更改最后一个也是唯一的维度。但是,如果您的数组有两个或更多维度,则您可以在使用 Preserve 的情况下仅更改最后一个维度的大小。