2015-11-02 66 views
2

使用访问VBA和我似乎无法增加2d动态数组。这似乎是一件容易的事,但我一直 “下标越界” 的错误@VBA阵列不能递增大小

使用ReDim保留affected_CAN_sat(this_array_index,4)

我的代码:

Dim this_array() as Variant 
ReDim this_array(0,4) 

Dim this_array_index As integer 
this_array_index = Ubound(this_array) 'index = 0 

dim n as integer 
For n = 0 to x ' x is unknown integer 
this_array_index = this_array_index + 1 
ReDim Preserve this_array(this_array_index,4) 
Next 

它应该有增加了数组的大小,但它没有。请帮助

回答

1

MSDN articleReDim

  • 与保留调整大小。如果使用保留,则只能调整数组的最后一个维度。对于其他维度,您必须指定现有数组的边界。

话虽这么说,你的代码的逻辑是没有意义的 - 如果你知道你循环是要增加的数量和数组的上边界会由一个增加每一次,然后就初始化正确的上边界,而不是循环数组:代替

For n = 0 to 10 '// <~~ We know this will only go up to 10 
    this_array_index = this_array_index + 1 
    ReDim Preserve affected_CAN_sat(this_array_index,4) 
Next 

如果你知道你只是要循环到10则j ust do:

Dim affected_CAN_sat() As Variant 
... 
this_array_index = this_array_index + 10 
ReDim Preserve affected_CAN_sat(0 To this_array_index, 0 To 4) As Variant 
... 

无需循环。

+0

对不起,我以10为例。真正的情况将是一个未知的数字高达4000. –

+0

你必须知道这个数字,但在代码的这一点,以便使用'For/Each'循环? –

+0

我知道,但为了解决主要问题,我选择了很少考虑它。然而,回到你以前的观点,为什么ReDim无法正常工作。 ReDim是否有任何可能的解决方案只有数组的大小? –