VBA 数组不能增加大小
VBA array can't increment size
使用访问 VBA,我似乎无法递增二维动态数组。这似乎是一项简单的任务,但我保留 "Subscript out of range" 错误 @
ReDim Preserve 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
它应该增加数组大小,但它没有。请帮忙
来自 MSDN article ReDim
- Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array. For every other dimension, you must specify the bound of the existing array.
也就是说,您的代码逻辑毫无意义 - 如果您知道循环要递增到的数字并且数组的上边界每次都会增加 1,那么只需初始化具有正确上边界而不是循环的数组:
而不是:
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,那么就这样做:
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
...
无需循环
使用访问 VBA,我似乎无法递增二维动态数组。这似乎是一项简单的任务,但我保留 "Subscript out of range" 错误 @
ReDim Preserve 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
它应该增加数组大小,但它没有。请帮忙
来自 MSDN article ReDim
- Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array. For every other dimension, you must specify the bound of the existing array.
也就是说,您的代码逻辑毫无意义 - 如果您知道循环要递增到的数字并且数组的上边界每次都会增加 1,那么只需初始化具有正确上边界而不是循环的数组:
而不是:
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,那么就这样做:
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
...
无需循环