API reference · Arrays
DimReduce
Convert a single-row or single-column 2D array into a 1D array.
Signature#
Function DimReduce(ByVal vArr As Variant) As VariantParameters#
| Parameter | VBA type | Default | Description |
|---|---|---|---|
vArr | VariantByVal | Required | Allocated 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#
Before
amountColumn2D · 3 × 1
Rows 5..7 · Columns 1..1
| row / col | 1 |
|---|---|
| 5 | 120 |
| 6 | 80 |
| 7 | 50 |
After
amounts1D · (3,)
Indices 5..7 · one dimension
| 5 | 6 | 7 |
|---|---|---|
| 120 | 80 | 50 |
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.
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 SubBehavior and edge cases#
- The single-row branch is checked first. For a 1 × 1 array, the sole output subscript comes from the source column bound.
- A general matrix is not flattened. It returns Empty when neither dimension has exactly one element.
- The remaining dimension's lower and upper bounds are preserved, and values stay in source order.
- Empty, Null and error-valued elements are copied. The input array is not modified.
Performance#
O(n) time and O(n) output storage, where n is the length of the surviving dimension.
View implementation
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