我写了一些代码,应该用值填充多维数组。初始数组的大小为1000x1000,但最后应重新定义为所需的(实际使用的)大小。为此,我使用代码:
ReDim Preserve MultiArrPaerchen(LBound(MultiArrPaerchen, 1) To UBound(MultiArrPaerchen, 1), LBound(MultiArrPaerchen, 2) To n)
Application.WorksheetFunction.Transpose (MultiArrPaerchen)
ReDim Preserve MultiArrPaerchen(LBound(MultiArrPaerchen, 1) To UBound(MultiArrPaerchen, 1), LBound(MultiArrPaerchen, 2) To m)
Application.WorksheetFunction.Transpose (MultiArrPaerchen)
发生的情况是,数组的大小从1000x1000更改为1000x120(正确值),然后从更改为1000x18。因此,如果我正确看到此结果,则第一个转置不会执行任何操作,因为数组arent的尺寸已切换。 但是代码看起来正确吗?
非常感谢
答案 0 :(得分:1)
我认为我可能在对上一个问题的评论中提供了错误的信息。 Application.Transpose像任何函数一样返回转置的数组。它不会像ByRef参数那样“就地”处理它。
'NOT this was
Application.WorksheetFunction.Transpose (MultiArrPaerchen)
'Do it THIS WAY
MultiArrPaerchen = Application.WorksheetFunction.Transpose(MultiArrPaerchen)
FWIW,自动神奇添加的空间应该被视为表明该语法很奇怪。
第一个ReDim调整第二个排名;第二个等级是使用ReDim唱Preserve参数时唯一可以调整的等级。
第一个Transpose翻转第一个和第二个排名。现在,您可以重新调整原始的第一个等级,而不是最后一个等级。
第二个ReDim调整最后一个排名(原来是第一个)。
第二个Transpose接收翻转后的数组,并将其返回到其原始方向,并在两个列中都具有新尺寸。
Sub test()
Dim MultiArrPaerchen As Variant, m As Long, n As Long
m = 1000
n = 1000
ReDim MultiArrPaerchen(1 To m, 1 To n)
Debug.Print LBound(MultiArrPaerchen, 1) & " to " & UBound(MultiArrPaerchen, 1) & ", " & _
LBound(MultiArrPaerchen, 2) & " to " & UBound(MultiArrPaerchen, 2)
'results: 1 to 1000, 1 to 1000
'UBounbds for 1 to 18, 1 to 120
m = 18
n = 120
ReDim Preserve MultiArrPaerchen(LBound(MultiArrPaerchen, 1) To UBound(MultiArrPaerchen, 1), _
LBound(MultiArrPaerchen, 2) To n)
Debug.Print LBound(MultiArrPaerchen, 1) & " to " & UBound(MultiArrPaerchen, 1) & ", " & _
LBound(MultiArrPaerchen, 2) & " to " & UBound(MultiArrPaerchen, 2)
'results: 1 to 1000, 1 to 120
MultiArrPaerchen = Application.Transpose(MultiArrPaerchen)
Debug.Print LBound(MultiArrPaerchen, 1) & " to " & UBound(MultiArrPaerchen, 1) & ", " & _
LBound(MultiArrPaerchen, 2) & " to " & UBound(MultiArrPaerchen, 2)
'results: 120, 1 to 1000
ReDim Preserve MultiArrPaerchen(LBound(MultiArrPaerchen, 1) To UBound(MultiArrPaerchen, 1), LBound(MultiArrPaerchen, 2) To m)
Debug.Print LBound(MultiArrPaerchen, 1) & " to " & UBound(MultiArrPaerchen, 1) & ", " & _
LBound(MultiArrPaerchen, 2) & " to " & UBound(MultiArrPaerchen, 2)
'results: 1 to 120, 1 to 18
MultiArrPaerchen = Application.Transpose(MultiArrPaerchen)
Debug.Print LBound(MultiArrPaerchen, 1) & " to " & UBound(MultiArrPaerchen, 1) & ", " & _
LBound(MultiArrPaerchen, 2) & " to " & UBound(MultiArrPaerchen, 2)
'results: 1 to 18, 1 to 120
End Sub