API reference · Arrays

Transpose

Swap the two dimensions of a 2D array using explicit VBA loops.

FunctionArrays→VariantSource L111

Signature#

VBA
Function Transpose(ByVal vArr As Variant) As Variant

Parameters#

ParameterVBA typeDefaultDescription
vArrVariantByValRequiredAllocated 2D array. A scalar, a 1D array, or another rank returns Empty.

Returns#

Variant containing a 2D array. Output row bounds equal the source column bounds, and output column bounds equal the source row bounds. Returns Empty for unsupported inputs.

Example#

SEE THE TRANSFORMATIONSwap rows and columns
Before
quarterly2D · 3 × 1

Rows 1..3 · Columns 1..1

row / col1
1100
2120
3140
After
horizontal2D · 1 × 3

Rows 1..1 · Columns 1..3

row / col123
1100120140

Both dimension lengths and their bounds exchange places.

Shaded headers are array indices, not data. Quoted cells are text. Values shown are derived from the source, not an Excel execution.

VBA
Sub ExampleTranspose()
    Dim a As New Arrays
    Dim quarterly As Variant, horizontal As Variant

    ReDim quarterly(1 To 3, 1 To 1)
    quarterly(1, 1) = 100
    quarterly(2, 1) = 120
    quarterly(3, 1) = 140
    horizontal = a.Transpose(quarterly)
    Debug.Print horizontal(1, 1), horizontal(1, 3) ' Expected: 100, 140
End Sub

Behavior and edge cases#

Performance#

O(r × c) time and O(r × c) output storage for r rows and c columns.

View implementation
VBA
Function Transpose(ByVal vArr As Variant) As Variant
    'Transposes a two-dimensional array by swapping its rows and columns

    Dim vArr_Out        As Variant
    Dim iRow            As Long
    Dim iCol            As Long

    If Not IsArray(vArr) Then Exit Function
    If Me.DimCounter(vArr) <> 2 Then Exit Function
    ReDim vArr_Out(LBound(vArr, 2) To UBound(vArr, 2), LBound(vArr, 1) To UBound(vArr, 1))
    For iRow = LBound(vArr_Out, 1) To UBound(vArr_Out, 1)
        For iCol = LBound(vArr_Out, 2) To UBound(vArr_Out, 2)
            vArr_Out(iRow, iCol) = vArr(iCol, iRow)
        Next iCol
    Next iRow

    Transpose = vArr_Out
End Function