Excel VBA Sort Multiple Columns with Header
In this article
To sort multiple columns in Excel VBA while keeping the header row in place, use the Sort method on a Range and set Header:=xlYes. The quickest working pattern is: define the range with Range("A1:D100"), call .Sort, then add one Key1 and up to two more keys with Order1, Order2, Order3. This sorts the data by the first key, then breaks ties with the second and third keys, and leaves row 1 untouched as the header. The steps below show the exact syntax, how to make the range dynamic, and how to avoid the errors that trip people up.
What You'll Need
- Excel desktop (Windows or Mac) with the Developer tab enabled, or permission to open the VBA editor with Alt+F11 (Option+F11 on Mac).
- A worksheet with a header row in row 1 and data below it, with no completely blank rows or columns inside the data block.
- Basic familiarity with the VBA editor: inserting a module and running a macro.
Step-by-Step
- Open the VBA editor. Press Alt+F11 (Windows) or Option+F11 (Mac). In the Project pane, right-click your workbook, choose Insert > Module. A blank code window appears.
- Write the macro skeleton. Type
Sub SortMulti()and press Enter; the editor addsEnd Sub. All code goes between these lines. - Set the worksheet and range. Use a
Withblock so you only name the sheet once:
Replace the range and key cells with your actual columns.With ThisWorkbook.Worksheets("Sheet1") .Range("A1:D100").Sort _ Key1:=.Range("B2"), Order1:=xlAscending, _ Key2:=.Range("C2"), Order2:=xlAscending, _ Key3:=.Range("D2"), Order3:=xlDescending, _ Header:=xlYes End WithKey1is the primary sort column,Key2the tie-breaker, andKey3the final tie-breaker. The key cells can be any cell in the column below the header; using row 2 is conventional. - Make the range dynamic (recommended). Hard-coded row 100 breaks when data grows. Use
CurrentRegioninstead:With ThisWorkbook.Worksheets("Sheet1") .Range("A1").CurrentRegion.Sort _ Key1:=.Range("B1"), Order1:=xlAscending, _ Header:=xlYes End WithCurrentRegionexpands to the contiguous block around A1, including the header. If your data has blank rows or columns inside it,CurrentRegionstops early, so remove those gaps first or use a calculated last row instead. - Run the macro. Press F5 while the cursor is inside the Sub, or go back to Excel and use Developer > Macros, select
SortMulti, and click Run. The data reorders and row 1 stays as the header. - Confirm the header setting. If the header row gets sorted into the data,
Header:=xlYesis missing or the range starts below row 1. If the first data row is treated as a header, the range starts at row 1 but the sheet has no header, so change toHeader:=xlNo.
Menu and dialog labels in Excel can differ slightly by version, platform and region, but the VBA syntax above is stable across current desktop versions.
Common Mistakes
- Forgetting
Header:=xlYes. Excel then treats row 1 as data and sorts it into the list. This is the single most common cause of a corrupted header. - Using a key cell outside the range.
Key1:=.Range("B2")must sit inside the sorted range. A key in another column or sheet causes a run-time error or an unexpected sort. - Sorting only one column. Selecting
Range("B2:B100")and sorting reorders that column alone, breaking row integrity. Always sort the full data block, not a single column. - Hard-coding the last row. A fixed
"A1:D100"misses new rows and includes stale blanks. UseCurrentRegionor compute the last row withCells(Rows.Count, 1).End(xlUp).Row. - Leaving blank rows inside the data.
CurrentRegionand Excel's sort both stop at the first fully blank row, so part of the data stays unsorted. - Mixing up
Order1andKey1. Each key needs its matching order; a missing order defaults to ascending, which may not be what you intended.
Tips
- Sort by up to three keys with the
Sortmethod. For more levels, sort the least important key first and repeat, or useSortFieldswith additional fields. - Use
Application.ScreenUpdating = Falsebefore the sort and set it back toTrueafter, especially in loops over many sheets. - Sort a
ListObject(an Excel table) withListObjects("Table1").Sort.SortFieldsif your data is formatted as a table; tables expand automatically and keep the header. - Record a macro with the Macro Recorder while performing a manual multi-column sort, then clean up the generated code. It gives you exact key and order syntax for your version.
- Test on a copy of the workbook first. Sorting is destructive and cannot be undone by re-running the macro.
Troubleshooting
- Run-time error 1004. Usually a key cell outside the range, a protected sheet, or a range that includes merged cells. Unprotect the sheet and remove merges inside the data block.
- Header row sorted into the data. Add or correct
Header:=xlYesand make sure the range starts at row 1. - Only part of the data sorted. Check for blank rows or columns inside the block, or a hard-coded range that is too small. Switch to
CurrentRegionor a calculated last row. - Wrong column sorted. Key cells are relative to the sheet, not the range. Verify the column letter in each
Keyargument matches the intended column. - Macro does nothing. Confirm the code is in a standard module, the sheet name in the code matches the tab name exactly, and the workbook is not read-only.
- Sort order looks random. Mixed data types in a column (numbers stored as text, dates as text) sort inconsistently. Convert the column to a consistent type before sorting.
Frequently Asked Questions
Can I sort more than three columns in VBA?
Yes. The Sort method accepts three keys directly, but you can add more with the SortFields collection or by sorting least-important keys first and repeating the sort. For most datasets three keys are enough.
How do I sort by column header name instead of column letter?
Find the column with WorksheetFunction.Match("HeaderName", .Range("A1:Z1"), 0), then use that column index to build the key range. This keeps the macro working when columns are inserted or moved.
Does this work on Excel for Mac?
Yes. The VBA sort syntax is the same. Use Option+F11 to open the editor and check that the macro security setting allows macros to run.
Why does my sort ignore the header setting?
If the range does not start at row 1, or the first row is blank, Excel cannot detect a header. Start the range at the header row and ensure it contains text labels.
Can I sort a filtered range?
Yes, but sorting a filtered range reorders only the visible rows in some cases. Clear filters first, sort, then reapply the filter to avoid unexpected results.
How do I sort dates correctly?
Ensure the cells are real dates, not text. Use Order1:=xlAscending on a date column and check the cell format is Date; text dates sort alphabetically and appear out of order.