Excel VBA Sort by Multiple Columns: Step-by-Step Guide
In this article
You can sort a worksheet by multiple columns in Excel VBA using the Sort method with a SortFields collection: clear any existing sort fields, add one field per column with its key, sort order and optional custom order, then apply the sort to a defined range. The code below works in Excel 2010 and later on Windows and Mac; exact dialog labels in the Excel interface can differ slightly by version and region, but the VBA object model is stable.
What You'll Need
- Excel 2010 or later (Windows or Mac) with the Developer tab enabled: File > Options > Customize Ribbon > Main Tabs > check Developer. On Mac, Excel > Preferences > Ribbon & Toolbar.
- A worksheet with a clean data range: one header row, no blank rows or columns inside the data, and no merged cells.
- Basic familiarity with the Visual Basic Editor (VBE): press Alt+F11 on Windows, or Fn+Option+F11 on Mac, to open it.
- A saved copy of your workbook before running any macro that rearranges data.
Step-by-Step
- Open the Visual Basic Editor and insert a module. Press Alt+F11 (Windows) or Fn+Option+F11 (Mac). In the Project Explorer, right-click your workbook, choose Insert > Module. A blank code window appears.
- Write a macro that defines the range. Use
RangeorCurrentRegionto capture the data including headers. For example:
Replace "Sheet1" with your sheet name.Sub SortMulti() Dim ws As Worksheet Dim rng As Range Set ws = ThisWorkbook.Worksheets("Sheet1") Set rng = ws.Range("A1").CurrentRegionCurrentRegionexpands to the contiguous block around A1; if your data has gaps, set an explicit range such asws.Range("A1:E200"). - Clear any existing sort fields. Add
rng.Sort.SortFields.Clearbefore adding new fields. Without this, Excel may retain old sort criteria and throw an error or produce an unexpected order. - Add the first sort field. Use
rng.Sort.SortFields.Add Key:=rng.Columns(1), Order:=xlAscending. TheKeyargument is a range that must be a single column within the sort range.OrderacceptsxlAscendingorxlDescending. - Add additional fields in priority order. Each subsequent
Addcall becomes a lower-priority sort key:
The first field added is the primary sort; later fields break ties.rng.Sort.SortFields.Add Key:=rng.Columns(2), Order:=xlAscending rng.Sort.SortFields.Add Key:=rng.Columns(3), Order:=xlDescending - Apply the sort. Call the
Sortmethod withHeader:=xlYesso the first row is treated as headers and not sorted into the data:With rng.Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .Apply End With End SubMatchCasecontrols whether uppercase and lowercase are treated as equal;Orientationsets top-to-bottom (rows) versus left-to-right (columns). - Run the macro. Press F5 in the VBE, or return to Excel and use Developer > Macros, select
SortMulti, and click Run. Your data should now be sorted by the columns you specified, in the order you added them. - Verify and adjust. Check that headers stayed in row 1 and that ties are broken as expected. If not, review the order of your
Addcalls and confirm eachKeyrefers to a column insiderng.
Common Mistakes
- Forgetting to clear sort fields. Reusing a range that already has sort criteria can cause run-time error 1004 or unexpected results. Always call
SortFields.Clearfirst. - Using a Key outside the sort range. If
rngis A1:C100, a Key of column D will fail. Make sure every Key column is inside the range. - Omitting
Header:=xlYes. Without it, Excel may sort the header row into the data, corrupting the order and misaligning column meanings. - Assuming the first Add is the primary key. The order of
Addcalls defines priority: first added is primary. Adding fields in the wrong order gives the wrong grouping. - Sorting a range with blank rows or merged cells. Blank rows split the data; merged cells prevent a clean sort. Remove them or sort each contiguous block separately.
- Hard-coding sheet names. If the sheet is renamed, the macro fails. Use the sheet's code name or prompt the user, or reference
ActiveSheetif appropriate.
Tips
- Use
rng.Columns(n)rather than absolute addresses likeRange("B1")so the macro keeps working if you insert columns later. - For custom lists (e.g., Low, Medium, High), set
Order:=xlAscendingand addCustomOrder:=with a comma-separated string, or useOrderCustomwith the list index. - To sort left-to-right (columns instead of rows), set
Orientation:=xlLeftToRightand use row-based keys. - Store the sort configuration in variables so you can reuse the same macro for different sheets or ranges.
- Test on a copy first. Sorting is destructive to row order; keep a backup until the macro is verified.
Troubleshooting
- Run-time error 1004 "The sort reference is not valid". Usually a Key outside the range, a range with no data, or a missing header setting. Check that
rngincludes all Key columns and thatHeaderis set. - Headers got sorted into the data. Add or correct
.Header = xlYes. If the header row contains blanks, Excel may not detect it; fill in header labels or use an explicit range that excludes the header and setHeader:=xlNo. - Sort order is wrong despite correct code. Confirm the order of
Addcalls. Also check for leftover sort fields from a previous run; clear them. - Macro runs but nothing changes. Ensure
.Applyis called and that the worksheet is not protected. Unprotect the sheet or run the macro on an unprotected copy. - Data appears misaligned after sorting. This often means the range included only part of the table. Expand
rngto cover all columns, or use a named range that covers the full table.
Frequently Asked Questions
Can I sort by more than three columns?
Yes. The SortFields collection accepts many fields; add as many as you need. The practical limit is the number of columns in your range.
How do I sort a table (ListObject) instead of a plain range?
Use the table's Sort property: ActiveSheet.ListObjects("Table1").Sort.SortFields.Add with the same Key, Order and Header arguments, then call .Apply.
Does this work on Excel for Mac?
Yes, the VBA sort object model is the same on Mac. Use Fn+Option+F11 to open the VBE. Some older Mac versions may have minor UI differences, but the code runs unchanged.
Can I sort by cell color or font color?
Yes. Use SortOn:=xlSortOnCellColor or xlSortOnFontColor and set SortOnValue.Color to the desired color. This is useful for flagging rows before sorting.
Why does my macro sort only part of the data?
Your range likely stops short. Check that rng covers every column and row of the table. CurrentRegion stops at blank rows or columns, so remove gaps or set an explicit range.
Can I undo a VBA sort?
Not with Ctrl+Z after the macro runs. Save a backup before running, or have the macro copy the original range to a hidden sheet first so you can restore it.