如何在Excel VBA中将Transpose函数基索引设置为0?

问题描述 投票:0回答:1

在我的 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 
arrays excel vba worksheet-function
1个回答
0
投票
  • a) 正如 BigBen 提到的,您不会通过
    WorksheetFunction.Transpose
    或评估
  • 更改基于 1 的结果
  • b) 您可以更改,但逻辑过程考虑到 1) Listbox 对象默认是从零开始的,但也接受其他边界 2) 它的
    .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
© www.soinside.com 2019 - 2024. All rights reserved.