Redim Preserve gives 'subscript out of range'

折月煮酒 提交于 2019-12-23 23:17:10

问题


I want to Redim Preserve an array I keep getting the error 'subscript out of range'. I am aware of the fact that only the size of the last dimension can be changed. That is exactly what I am doing. What is going wrong over here? The type of the array is Variant.

BmMatrix = Sheets("BENCH").Range("a60", ActiveSheet.Range("a60").End(xlDown).End(xlToRight))
'totaal gewicht per subdeel in array wegschrijven
Dim aBmMatrix()
aBmMatrix = BmMatrix
rij = UBound(BmMatrix, 1)
kol = UBound(BmMatrix, 2) + 1
ReDim Preserve aBmMatrix(rij, kol)
TotGewKol = UBound(aBmMatrix, 2)
For i = 2 To UBound(BmMatrix, 1)
    g = 0 'g wordt totaal gewicht van land bv
    If BmMatrix(i, bm_kolom) <> "x" Then
        For j = 2 To UBound(bmexnul, 1)
            If bmexnul(j, weightkolom) = BmMatrix(i, bm_kolom) Then g = g + bmexnul(j, 10)
        Next j
    End If
    aBmMatrix(i, TotGewKol) = g
    aBmMatrix(1, TotGewKol) = "Totaal gewicht" 'titel kolom
Next i

回答1:


Because you assign aBmMatrix array using the Value property of a range, the returned array has lower bounds of 1 for each dimension.

When you later redim it without providing lower bounds explicitly, the redim tries to assign each dimension the default lower bound, which is 0.

You need to explicitly provide the lower bounds:

ReDim Preserve aBmMatrix(lbound(aBmMatrix,1) to rij, lbound(aBmMatrix,2) to kol)



回答2:


You can only use preserve when you change only the last dimension of an array.



来源:https://stackoverflow.com/questions/14055734/redim-preserve-gives-subscript-out-of-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!