在我的 VBA 代码中,我使用 WorksheetFunction 类的 Transpose 函数。我注意到,即使应用程序的选项基数是默认的 0 值,WorksheetFunction.Transpose() 也会返回从 1 开始索引的数组。
如果在 Excel 工作表或具有范围的 VBA 中使用它,这不会造成任何问题,但当该函数应用于任何类型的数组时,会有点令人惊讶。现在,我重新索引新数组中的值,以便与程序中的其他数组兼容。
是否有参数或设置将数组索引基值设置为 0,或由 WorksheetFunction.Transpose 生成的应用程序的选项基值?
这是测试:
Sub arrtra()
Dim arr(5, 2)
Dim res As Variant
For i = 0 To 5
For j = 0 To 2
arr(i, j) = Rnd()
Next j
Next i
res = arr
tra = tes(res)
Debug.Print "Ubound="; UBound(arr, 1), "Ubound="; UBound(tra, 2), arr(0, 0), tra(1, 1)
End Sub
Function tes(vmi As Variant) As Variant
tes = WorksheetFunction.Transpose(vmi)
End Function
这是测试的打印结果:
Ubound= 5 Ubound= 6 0,7055475 0,705547511577606
WorksheetFunction.Transpose
或评估.Column
属性能够将任何内容输入(通过 .List 属性输入)返回到 基于零的 输出。最终您可能会受益于这一切都可以在内存中完成的事实 - 请参阅
TransposeZerobased(arr)
函数:-)
Function TransposeZerobased(arr)
'Purp: transpose a 2D array into a zerobased one
'Note: expects a 2D array input into a ListBox referred to in memory
transposed data
With CreateObject("New:{8BD21D20-EC42-11CE-9E0D-00AA006002F3}") ' listbox only in memory
.List = arr ' assign array to list property
TransposeZerobased = .Column ' transpose via Column property
End With
End Function
Sub FillRndArr(arr)
Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
Dim j As Long
For j = LBound(arr, 2) To UBound(arr, 2)
arr(i, j) = Rnd()
Next j
Next i
End Sub
调用示例
Sub ExampleCall()
Dim arr(0 To 5, 0 To 2)
FillRndArr arr ' fill 2D array with randomized content
Dim tra
tra = TransposeZerobased(arr) ' << execute transposition
End Sub