Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA: Sort an Array by Multiple Columns

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Excel VBA cannot sort an array by multiple columns in one command. The built-in Sort method belongs to ranges and ListObjects, not to arrays, and Application.WorksheetFunction.Sort (available in newer Excel versions that have dynamic arrays) returns a new array sorted by only one key unless you pass a dedicated by_col argument that applies to columns, not to multiple sorting keys. To sort a two-dimensional array by several fields — say region, then date, then amount — you need to write the comparison logic yourself. The most reliable approach is a simple insertion sort or quicksort routine with a custom comparison function that walks through a list of key columns and breaks ties on the next key. This keeps everything in memory, avoids writing to a worksheet, and works on both 32-bit and 64-bit Office.

The method below builds a reusable sorter for a 2D variant array (rows = records, columns = fields), with ascending and descending options per key. It is the version that survives real data: messy ties, mixed types, empty cells and arrays read straight from a range.

What You'll Need

  • Excel on Windows or Mac with macros enabled, and access to the Visual Basic Editor (Alt+F11 on Windows, or Tools > Macro > Visual Basic Editor on Mac; menu names can vary slightly by version).
  • A workbook saved as .xlsm (macro-enabled) or .xlsb, since .xlsx cannot store VBA.
  • A data set with a clear header row, ideally loaded into a variant array with Range.Value rather than read cell by cell.
  • A decision on your sort keys: which column holds the primary field, which one breaks ties, and whether each is ascending or descending.
  • Comfort with basic VBA syntax: loops, arrays, LBound/UBound, and Option Base 1 awareness.

Step-by-Step

  1. Open the editor and add a module. Press Alt+F11, then Insert > Module. Keep the sorter in a standard module so any procedure in the project can call it.
  2. Read the data into a variant array. Assuming data sits in A1:D200 with headers in row 1, use Dim data As Variant then data = ws.Range("A2:D200").Value2. Arrays read this way are always 1-based on both dimensions, even if Option Base 0 is in force, so start loops at LBound(data, 1) rather than at 0.
  3. Store your keys in a small structure. Declare two parallel arrays: one holding the column indexes (e.g. keyCols = Array(1, 3, 2)) and one holding direction flags (keyDesc = Array(False, False, True)). Column indexes refer to positions inside the variant array, not to worksheet letters, so column C is index 3.
  4. Write a comparison function. Create Function CompareRows(a, b, keyCols, keyDesc) As Long. Loop over each key, read a(idx) and b(idx), compare them, and return -1, 1 or 0 on the first difference. If every key matches, return 0 so the sort leaves the rows in their existing relative order.
  5. Handle types inside the comparison. Use IsEmpty and Len(Trim$(CStr(...))) to push blanks to the end regardless of direction, and use StrComp with vbTextCompare for text so "apple" and "Apple" tie. For dates, check IsDate and compare the converted values so a date stored as text sorts alongside a real date.
  6. Apply the direction flag. After computing the raw comparison for a key, flip the sign if the matching keyDesc entry is True: CompareRows = result * -1. Do the flip per key, not once at the end, or the tie-breaking order breaks.
  7. Sort with insertion sort. For each row from LBound(data,1) + 1 to UBound(data,1), copy the row into a temporary one-dimensional array, then shift preceding rows right while CompareRows(tempRow, data(j), ...) < 0, and drop the temporary row into the gap. Use a helper CopyRow sub to move values between the 2D array and the temp row. Insertion sort is stable, which is exactly what multi-key sorting needs.
  8. Call the routine. Pass the array, the key lists and the bounds into a public SortArray2D procedure. Keep the key lists as parameters, not hard-coded constants, so the same routine serves every sheet in the workbook.
  9. Write the result back. Use ws.Range("A2").Resize(UBound(data,1), UBound(data,2)).Value2 = data to dump the sorted array in one operation. Writing the whole block at once is far faster than looping through cells.
  10. Test with duplicate keys. Build a small sample where two rows share the primary key and check that the secondary key orders them correctly, and that two rows identical on all keys keep their original order.

Common Mistakes

  • Mixing up LBound bases. Arrays from Range.Value are 1-based, but arrays created with Dim x(10) follow Option Base. Hard-code LBound and UBound calls instead of assuming 0 or 1.
  • Sorting with the built-in Sort on an array. Range.Sort is a method of a Range object; calling it on a Variant array throws a type mismatch.
  • Applying the descending flip once. Flipping the final result negates only the last key's comparison, so ties on earlier keys come out wrong. Flip inside the key loop.
  • Comparing variants with < and > blindly. A numeric value against a text value gives a run-time error 13 (type mismatch) rather than a sensible order. Normalise types in the comparison function.
  • Forgetting to resize the write-back range. Writing a 4-column array into a 3-column range trims silently or errors, depending on context. Always Resize to both bounds.
  • Using bubble sort on large data. Fine for a few hundred rows, painfully slow for tens of thousands. Insertion sort is acceptable; a quicksort or merge sort is better beyond roughly 10,000 rows.

Tips

  • If you only need one sort per session and the data lives in a worksheet, sorting the range with Range.Sort and multiple Key1, Key2 and Order1, Order2 arguments is simpler and faster than any in-memory routine. Use the array method only when the data must stay off the sheet.
  • Build a small SortKey wrapper (column, direction, type) so adding a fourth key is one line, not several parallel arrays to keep in sync.
  • For text keys, add Trim$ or UCase$ inside the comparison so stray spaces do not create phantom groups.
  • Test with Debug.Print on the comparison function for the first few rows; it makes tie-breaking bugs obvious.
  • Keep the sorter in a separate module and give it a clean public signature so other projects can import it unchanged.

Troubleshooting

If the macro errors with "Subscript out of range" (error 9), your key column index is outside LBound(data, 2) to UBound(data, 2), usually because you counted worksheet columns starting at zero. Print the upper bound and compare.

If the output looks sorted but rows are shuffled within equal keys, your sort is not stable or the direction flip is in the wrong place. Switch to insertion sort and flip inside the key loop.

If numbers sort as text (100 before 20), the cells were read as strings. Either convert with CDbl in the comparison or fix the source data, which is usually faster.

If dates land at the wrong end, check whether they are stored as real dates or text. IsDate catches the text case, but mixed formats such as dd/mm/yyyy versus mm/dd/yyyy will still sort wrongly — standardise the source column first.

If the write-back overwrites headers or leaves the last row behind, the range and array sizes disagree. Resize from the first data row to UBound on both dimensions and verify the header row is excluded.

If nothing happens at all, macros may be disabled by Trust Center settings, or the procedure name you called does not match (check for a trailing space). Reopen the file and enable macros before rerunning.

Frequently Asked Questions

Can I sort an array by multiple columns without writing a sort routine?

Not directly. Excel's array functions sort by one key. Write the array to a spare range, sort the range with multiple keys, read it back, or accept a single-key sort.

Is Application.WorksheetFunction.Sort a multi-key sort?

No. It sorts on the values you supply and takes an optional by_col flag that changes whether rows or columns are sorted, not how many keys are used.

Which sort algorithm should I use?

Insertion sort for a few hundred to a few thousand rows because it is stable and simple. Use a merge sort or quicksort above that, and add a stable tie-break by original row index if order within equal keys matters.

How do I sort descending on the second key but ascending on the first?

Give each key its own direction flag and apply the sign flip only to the key being compared, inside the loop, not once at the end.

Do 2D arrays always start at 1?

Arrays returned by Range.Value and .Value2 do, regardless of Option Base. Arrays you declare yourself follow the module's base. Use LBound and UBound everywhere.

Will this work on Excel for Mac?

Yes, the VBA language and array handling are the same. The editor shortcut and menu wording differ, but the code runs unchanged.