提问人:Black cat 提问时间:8/31/2023 更新时间:9/1/2023 访问量:105
如何在Excel VBA中将转置函数基索引设置为0?
How can set the Transpose function base index to 0 in Excel VBA?
问:
在我的 VBA 代码中,我使用 WorksheetFunction 类的 Transpose 函数。我注意到,即使应用程序的 Option Base 是默认的 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
答:
4赞
T.M.
8/31/2023
#1
- a) 正如 BigBen 所提到的,您不会通过或评估来更改从 1 开始的结果
WorksheetFunction.Transpose
- b) 您可以更改逻辑过程,但考虑到 1) 默认情况下,Listbox 对象是从零开始的,但也接受其他边界 2)
它的属性能够返回任何内容输入(通过 .List 属性)转换为从零开始的转置输出。
.Column
最终,您可能会从以下事实中获益:这一切都可以在内存中完成 - 请参阅函数:-)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
评论