API reference · Arrays

DimReduce

Convert a single-row or single-column 2D array into a 1D array.

FunctionArrays→VariantSource L256

Signature#

VBA
Function DimReduce(ByVal vArr As Variant) As Variant

Parameters#

ParameterVBA typeDefaultDescription
vArrVariantByValRequiredAllocated 2D array with exactly one row or exactly one column.

Returns#

Variant containing a 1D array. A single row uses the source column bounds; a single column uses the source row bounds. Returns Empty for non-arrays, other ranks, or a matrix with multiple rows and multiple columns.

Example#

SEE THE TRANSFORMATIONRemove the single-column dimension
Before
amountColumn2D · 3 × 1

Rows 5..7 · Columns 1..1

row / col1
5120
680
750
After
amounts1D · (3,)

Indices 5..7 · one dimension

567
1208050

A 1D vector has one index per element. It is drawn horizontally here for readability; it is not a 1 × 3 matrix.

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

VBA
Sub ExampleDimReduce()
    Dim a As New Arrays
    Dim amountColumn As Variant, amounts As Variant

    ReDim amountColumn(5 To 7, 1 To 1)
    amountColumn(5, 1) = 120
    amountColumn(6, 1) = 80
    amountColumn(7, 1) = 50
    amounts = a.DimReduce(amountColumn)
    Debug.Print LBound(amounts), UBound(amounts) ' Expected: 5, 7
    Debug.Print amounts(6)                    ' Expected: 80
End Sub

Behavior and edge cases#

Performance#

O(n) time and O(n) output storage, where n is the length of the surviving dimension.

View implementation
VBA
Function DimReduce(ByVal vArr As Variant) As Variant
    'Converts a single-row or single-column 2D array into a 1D array

    Dim vArr_Out                As Variant
    Dim lRow                    As Long
    Dim lCol                    As Long

    If Not IsArray(vArr) Then Exit Function
    If Me.DimCounter(vArr) <> 2 Then Exit Function

    If LBound(vArr, 1) = UBound(vArr, 1) Then
        ReDim vArr_Out(LBound(vArr, 2) To UBound(vArr, 2))
        For lCol = LBound(vArr, 2) To UBound(vArr, 2)
            vArr_Out(lCol) = vArr(LBound(vArr, 1), lCol)
        Next lCol
    ElseIf LBound(vArr, 2) = UBound(vArr, 2) Then
        ReDim vArr_Out(LBound(vArr, 1) To UBound(vArr, 1))
        For lRow = LBound(vArr, 1) To UBound(vArr, 1)
            vArr_Out(lRow) = vArr(lRow, LBound(vArr, 2))
        Next lRow
    Else
        Exit Function
    End If

    DimReduce = vArr_Out
End Function