[英]2D Array subscript out of range on ReDim
I have a 2D array in VBA (Excel 365).我在 VBA (Excel 365) 中有一个二维数组。
It gives me an error message Subscript out of Range
它给了我一条错误消息
Subscript out of Range
The code stops at the ReDim line.代码在 ReDim 行停止。
ReDim arrs(1 To 1, 1 to 6) As Variant
For idx = 1 To lr
If staff_group(idx) = "" Then Exit For
If InStr(LCase(staff_group(idx)), "al - ") Then
arrs(UBound(arrs,1), 1) = sg(idx)
arrs(UBound(arrs,1), 2) = nd(idx)
arrs(UBound(arrs,1), 3) = intv(idx)
arrs(UBound(arrs,1), 4) = rq(idx)
arrs(UBound(arrs,1), 5) = prd(idx) + id(idx)
arrs(UBound(arrs,1), 6) = IIfw(idx) = "Y", "1", IIfh(idx) = "-1", "OVR", ""))
ReDim Preserve arrs(1 To UBound(arrs,1) + 1, 1 to 6)
End If
Next
My working code below:我的工作代码如下:
ReDim arrs(1 To 1) As Variant
For idx = 1 To lr
If staff_group(idx) = "" Then Exit For
If InStr(LCase(staff_group(idx)), "al - ") Then
ReDim temp(6) As Variant
temp(0) = sg(idx)
temp(1) = nd(idx)
temp(2) = intv(idx)
temp(3) = rq(idx)
temp(4) = prd(idx) + id(idx)
temp(5) = IIf(waive(idx) = "Y", "1", IIf(hold(idx) = "-1", "OVR", ""))
arrs(UBound(arrs)) = temp
ReDim Preserve arrs(1 To UBound(arrs) + 1)
End If
Next
you may want to use ReDim
statement as few times as possible您可能希望尽可能少地使用
ReDim
语句
Dim arrDim As Long ' long value to store arrs actual dimension
ReDim arrs(1 To lr) As Variant ' initial dimming of arrs to its maximum possible size
For idx = 1 To lr
If staff_group(idx) = "" Then Exit For
If InStr(LCase(staff_group(idx)), "al - ") Then
ReDim temp(6) As Variant
temp(0) = sg(idx)
temp(1) = nd(idx)
temp(2) = intv(idx)
temp(3) = rq(idx)
temp(4) = prd(idx) + ID(idx)
temp(5) = IIf(waive(idx) = "Y", "1", IIf(hold(idx) = "-1", "OVR", ""))
arrDim = arrDim + 1 ' update arrs currently needed size
arrs(arrDim) = temp ' update arrs item at currently needed size index
End If
Next
ReDim Preserve arrs(1 To arrDim + 1) ' finally, redim arrs to final size
Please note that ReDim Preserve arrs(1 To arrDim + 1)
leads to an empty arrs
last item, as per your example.请注意,
ReDim Preserve arrs(1 To arrDim + 1)
导致空arrs
最后一个项目,按你的例子。
Shouldn't you need it, then just use ReDim Preserve arrs(1 To arrDim)
你不应该需要它,然后只需使用
ReDim Preserve arrs(1 To arrDim)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.