Guides

Sort a table by column

Sort complete records while preserving the order of equal keys.

Choose a column and direction#

Sort uses a stable merge sort of row indices, then copies the rows into a new array. Direction 1 is ascending and 0 is descending. Equal keys retain their original order.

SEE THE TRANSFORMATIONAmount descending · column 1
Before
records2D · 3 × 2

Rows 0..2 · Columns 0..1

row / col01
0“TX-001”120
1“TX-002”80
2“TX-003”120
After
sorted2D · 3 × 2

Rows 0..2 · Columns 0..1

row / col01
0“TX-001”120
1“TX-003”120
2“TX-002”80

The tie at 120 preserves TX-001 before TX-003. Bounds stay 0-based.

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

VBA
Sub SortTransactions()
    Dim records As Variant, sorted As Variant
    records = Arr.DimMerge(VBA.Array( _
        VBA.Array("TX-001", 120), VBA.Array("TX-002", 80), _
        VBA.Array("TX-003", 120)))
    sorted = Arr.Sort(records, 1, 0) ' Amount column index 1, descending
    Debug.Print sorted(0, 0) ' Expected: TX-001
    Debug.Print sorted(1, 0) ' Expected: TX-003 (stable tie)
    Debug.Print sorted(2, 0) ' Expected: TX-002
End Sub

Comparison and bounds#

The source uses native VBA > and < comparisons. It does not normalize errors, Nulls, mixed types, or numeric text. Clean a sort key to a consistent comparable type first. There is no Option Compare declaration in Arrays, so native text comparisons use the default binary mode. The source array remains unchanged, and successful results preserve its bounds and rank (1D or 2D).

The column parameter is an Integer. A negative column selects the source’s first column; it cannot directly select a negative-index column other than the first. An out-of-range column returns Empty. Any direction other than 0 or 1 returns the original data without sorting.

Cost#

For r rows and c columns, sorting uses O(r log r + rc) time and O(r + rc) working/output space. The index merge uses two Long arrays and a logarithmic recursion stack.