Smart Systems for Home

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

Excel VBA Sort Multiple Keys: Step-by-Step Guide

· 6 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

To sort multiple keys in Excel VBA, use the Sort method on a Range object and add each key with SortFields.Add, specifying the key range, sort order, and orientation. The minimal working pattern is Range("A1:D100").Sort Key1:=Range("B1"), Order1:=xlAscending, Key2:=Range("C1"), Order2:=xlDescending, Header:=xlYes. For more than three keys, or when you need to control each key's orientation and custom order, use SortFields explicitly. This guide walks through both approaches, plus the mistakes that cause runtime errors and silent mis-sorts.

What You'll Need

  • Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > check Developer, or Excel > Preferences > Ribbon & Toolbar on Mac).
  • A worksheet with a contiguous data block and a header row. Sorting works best when there are no blank rows or columns inside the range.
  • Basic familiarity with the VBA editor (Alt+F11 on Windows, Option+F11 on Mac). Menu labels can differ slightly by version and platform.

Step-by-Step

  1. Open the VBA editor and insert a module. Press Alt+F11 (Windows) or Option+F11 (Mac), then choose Insert > Module. A new blank module appears in the Project Explorer.
  2. Write a Sub that targets the exact range. Avoid ActiveRegion unless you know the data is contiguous. A reliable pattern is to compute the last row and last column, then build the range. For example: Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data") and Dim lastRow As Long: lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row. Then Set rng = ws.Range("A1").Resize(lastRow, 4).
  3. Decide whether to use the shortcut form or SortFields. The shortcut form (Key1, Order1, Key2, Order2, Key3, Order3) is fine for up to three keys. For four or more keys, or when you need per-key orientation, use SortFields.
  4. Clear any previous sort state. Call ws.Sort.SortFields.Clear before adding keys. If you skip this, Excel may retain keys from a previous sort and produce unexpected results.
  5. Add each key with SortFields.Add. The signature is SortFields.Add Key:=Range, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal. Repeat for each key in priority order: the first key added is the primary sort, the second is the tie-breaker, and so on. For example: With ws.Sort: .SortFields.Clear: .SortFields.Add Key:=ws.Range("B2:B" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending: .SortFields.Add Key:=ws.Range("C2:C" & lastRow), SortOn:=xlSortOnValues, Order:=xlDescending: .SetRange rng: .Header = xlYes: .MatchCase = False: .Apply: End With.
  6. Set the range, header, and orientation on the Sort object. Use .SetRange rng, .Header = xlYes (or xlNo if your data has no header row), and .Orientation = xlTopToBottom for normal column sorting. Then call .Apply. The Apply call is what actually performs the sort; forgetting it is a common cause of "nothing happened."
  7. Run the macro. Press F5 in the editor or assign the Sub to a button. Check that the header row stayed in place and that ties on the primary key are broken by the secondary key as intended.
  8. Optional: sort by custom list or cell color. For custom order, set Order:=xlAscending and add CustomOrder:="Low,Medium,High". For color, use SortOn:=xlSortOnCellColor and supply Order:=xlAscending with the target color. These options exist on the Sort object but are easy to misconfigure; test on a copy first.

Common Mistakes

  • Using Key1/Key2 with more than three keys. The shortcut form only accepts three keys; a fourth key silently does nothing or raises an error depending on how it is written. Switch to SortFields.
  • Forgetting SortFields.Clear. Previous keys persist on the worksheet's Sort object, so a second run can sort by stale criteria.
  • Passing a full column as the key. Key:=ws.Columns("B") can produce a mismatch error or sort blank rows. Use the data range, e.g. ws.Range("B2:B" & lastRow).
  • Setting Header incorrectly. If Header = xlNo on data that has a header, the header row gets sorted into the data. If xlYes on data without one, the first data row is treated as a header and excluded.
  • Omitting .Apply. Configuring the Sort object does nothing until Apply is called.
  • Sorting a range that includes blank rows or merged cells. Merged cells in the sort range raise errors; unmerge or exclude them first.

Tips

  • Record a macro while performing a multi-key sort manually, then read the generated code. It shows the exact SortFields syntax Excel expects for your version.
  • Store the key column letters in variables so the same Sub can be reused across sheets: Dim key1Col As String: key1Col = "B".
  • Use Application.ScreenUpdating = False before the sort and restore it to True afterward when sorting large ranges in a loop.
  • Test on a copy of the workbook. Sorting is destructive and there is no undo inside a running macro.
  • If you need to preserve the original order, copy the range to a hidden sheet before sorting.

Troubleshooting

  • "The sort reference is not valid" error. Usually caused by a key range that does not match the SetRange dimensions, or by a key that points outside the sort range. Confirm every key column lies inside the range passed to SetRange.
  • Nothing happens after running the macro. Check that .Apply is present and that the Sub actually ran (add a MsgBox "done" temporarily). Also confirm the worksheet reference is correct; the code may be sorting a different sheet than the one you are viewing.
  • Header row gets sorted into the data. Set .Header = xlYes and make sure the range starts at the header row, not the first data row.
  • Secondary key is ignored. The secondary key only breaks ties on the primary key. If the primary key values are all unique, the second key has no visible effect. Verify with duplicate values in the primary column.
  • Runtime error 1004 on merged cells. Unmerge cells in the range or exclude them; VBA sorting does not support merged cells inside the sort range.
  • Sort order looks wrong for text. Excel sorts text case-insensitively by default and may treat numbers stored as text differently from real numbers. Set .MatchCase and convert text-numbers to numbers before sorting.

Frequently Asked Questions

Can I sort by more than three keys in VBA?

Yes. The Key1/Key2/Key3 shortcut is limited to three, but the SortFields collection accepts any number of keys. Add them in priority order and call Apply.

How do I sort one key ascending and another descending?

Set the Order parameter per key: Order:=xlAscending for the first and Order:=xlDescending for the second. Each SortFields.Add call carries its own Order.

Does VBA sorting respect a header row automatically?

No. You must set .Header = xlYes or xlNo explicitly. Excel does not infer it from the data when sorting through VBA.

Can I sort by cell color or font color with multiple keys?

Yes, using SortOn:=xlSortOnCellColor or xlSortOnFontColor on a given key, combined with other value-based keys. Configure and test on a copy first, as color sort behavior can vary by version.

Why does my macro sort the wrong sheet?

Because the code references ActiveSheet or an unqualified Range, which points at whatever sheet is active at runtime. Qualify every reference with a worksheet variable, e.g. ws.Range(...).

Can I undo a VBA sort?

Not with Ctrl+Z after the macro finishes. Save the workbook before running, or copy the original range to a backup sheet inside the macro so you can restore it.