vba Redim Preserve 给出“下标超出范围”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14055734/
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
Redim Preserve gives 'subscript out of range'
提问by Amir
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
.
我想要Redim Preserve
一个数组,我不断收到错误“下标超出范围”。我知道只有最后一个维度的大小可以更改。这正是我正在做的。这里出了什么问题?数组的类型是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
回答by GSerg
Because you assign aBmMatrix
array using the Value
property of a range, the returned array has lower bounds of 1
for each dimension.
因为您aBmMatrix
使用Value
范围的属性分配数组,所以返回的数组1
对于每个维度都有下限。
When you later redim it without providing lower bounds explicitly, the redim tries to assign each dimension the default lower bound, which is 0
.
当您稍后在未明确提供下限的情况下对其进行 redim 时,redim 会尝试为每个维度分配默认下限,即0
。
You need to explicitly provide the lower bounds:
您需要明确提供下限:
ReDim Preserve aBmMatrix(lbound(aBmMatrix,1) to rij, lbound(aBmMatrix,2) to kol)
回答by DMM Wallnut
You can only use preserve when you change only the last dimension of an array.
只有在仅更改数组的最后一维时才能使用保留。