Excel VBA Sort Data With Headers: Step-by-Step Guide
In this article
Sorting a range that has a header row is one of the most common Excel VBA tasks, and the safest way to do it is to set the Header argument to xlYes (or xlGuess) and let Excel treat the first row as labels rather than data. If you leave that argument out, VBA defaults to xlNo, so your column titles get shuffled into the middle of the sorted data and your sheet becomes unusable. The fix is a single argument, but it only works when the range is defined correctly, so the steps below cover both.
What You'll Need
- Excel on Windows or Mac with the Developer tab enabled, or any version that lets you open the VBA editor with Alt+F11 (Option+F11 on Mac).
- A worksheet with your data in one contiguous block, with column labels in the first row and no blank rows or blank columns inside the block.
- A macro-enabled workbook (.xlsm) if you want to keep the code. A plain .xlsx file will strip the module when you save.
Step-by-Step
- Open the VBA editor. Press Alt+F11 on Windows or Option+F11 on Mac. In the Project Explorer on the left, right-click your workbook, choose Insert > Module, and use the code window that appears. Menu and dialog labels can vary slightly by Excel version and platform, so if a name looks different, look for the closest equivalent.
- Write the procedure and declare your variables. Start with
Sub SortWithHeaders()and declare a worksheet and a range variable. UsingDimup front lets you refer to the range more than once without re-querying the sheet. - Point to the correct worksheet explicitly. Use
Set ws = ThisWorkbook.Worksheets("Sheet1")rather than relying onActiveSheet. Code that depends on whatever sheet happens to be in front is the number one reason a working sort suddenly scrambles the wrong tab. - Define the range from the header row down. The clean way is to start at A1 and extend to the last used cell:
Set rng = ws.Range("A1").CurrentRegion.CurrentRegionexpands outward from A1 until it hits a completely blank row or column, which makes it ideal for a solid table. If your table starts in a different cell, anchor the range there instead. - Call the Sort method with the header argument set. The minimal working line is
rng.Sort Key1:=ws.Range("A1"), Order1:=xlAscending, Header:=xlYes. Writingws.Range("A1")as the key means "sort by the column that holds the A1 label". You can also pass a column offset such asrng.Columns(2)to sort by the second column in the block. - Add a second key if you need a tie-breaker. Append
Key2:=ws.Range("B1"), Order2:=xlAscendingso rows with the same primary value fall into a predictable order. You can go up to three keys in one call. - Choose the right order constant. Use
xlAscendingfor A to Z or smallest to largest,xlDescendingfor the reverse. These are built-in Excel constants, not text strings, so leave them unquoted. - Handle text that looks like numbers. If a column contains values typed as text, an ascending sort can put "10" before "9". Decide deliberately whether to convert the column to real numbers first rather than letting the sort produce odd-looking order.
- Run the macro. Press F5 with the cursor inside the procedure, or use Run > Run Sub/UserForm. Watch the sheet to confirm the header row stayed at the top and the data rows moved as a unit.
- Test on a copy first. Duplicate the sheet before your first run. Sorting is destructive in the sense that it rearranges data in place, and Ctrl+Z inside a macro does not undo the sort the way it does when you sort manually.
- Save as a macro-enabled file. Use File > Save As and pick Excel Macro-Enabled Workbook. If you also want the sort to run from a button, insert a shape, right-click it, and assign the macro.
A complete, compact version of the code looks like this:
Sub SortWithHeaders()
Dim ws As Worksheet
Dim rng As Range
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set rng = ws.Range("A1").CurrentRegion
rng.Sort Key1:=ws.Range("A1"), Order1:=xlAscending, _
Key2:=ws.Range("B1"), Order2:=xlAscending, _
Header:=xlYes
End Sub
Common Mistakes
- Leaving out
Header. The default isxlNo, so your labels get treated as data. This is the single most frequent cause of a "sort broke my sheet" complaint. - Sorting a range that starts below the header row. If the range is A2:C100 but the labels are in row 1,
xlYestells Excel the first row of that range (row 2) is a header, and a real data row gets pinned in place. Always include row 1 in the range. - Using
xlGuesswithout checking. It lets Excel decide whether a header exists, which usually works but can guess wrong on a table whose first row looks like data. UsexlYeswhen you know a header exists. - Blank rows or columns inside the table. These silently truncate
CurrentRegion, so only part of the data gets sorted and the rest stays put. - Relying on
ActiveSheet. If the user clicks another tab before running the macro, the sort fires on the wrong sheet. - Forgetting that a sort does not adjust formulas the way you expect. Relative references inside the table move with their rows, but references from outside the sorted range keep pointing at the same cells, not the same records.
- Merged cells in the header. A merged header cell can make the sort fail or throw a runtime error. Unmerge before sorting.
Tips
- Convert the data to an Excel Table (Insert > Table) and sort the table's
ListObject. Tables carry their header automatically and expand as new rows are added, so the sort range never falls out of date. - Sort by column name instead of cell address where possible. A helper that finds the header with
Matchsurvives someone inserting a column on the left. - If you need the sorted result without disturbing the original, copy the range to a new location first, then sort the copy.
- Turn off screen updating with
Application.ScreenUpdating = Falseat the start and back toTrueat the end when sorting many sheets, then restore it even if an error occurs. - Keep the header argument explicit in every sort call, even when you are sure of the default. Future-you will thank you.
Troubleshooting
If the header row ends up in the middle of your data, the range almost certainly excluded row 1 or Header was omitted. Widen the range to include the labels and set Header:=xlYes.
If only some rows moved, a blank row or blank column is cutting CurrentRegion short. Select the table manually and check for gaps, then either fill them or define the range explicitly with ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol)).
If you get a runtime error about merged cells or the range, unmerge the header, then retry. If the error mentions the sheet name, confirm the tab name in your code matches the real tab exactly, including spaces.
If the macro runs but nothing seems to happen, check that the code is in a standard module (not a sheet or ThisWorkbook module), that macros are enabled, and that you edited and saved the .xlsm file rather than a read-only copy.
If the sort order looks wrong for numbers, the column is probably stored as text. Convert it to numeric values, or use a value-based sort, then run again. And if you cannot recover the original order, close without saving and reopen the file, since a macro-driven sort is not undone by Ctrl+Z.
Frequently Asked Questions
What does Header:=xlYes actually do?
It tells Excel that the first row of the range contains column labels, so that row is excluded from the sort and stays fixed at the top while the rows beneath it are reordered.
Should I use xlYes or xlGuess?
Use xlYes when you know a header row exists. xlGuess asks Excel to detect it, which is convenient for ad-hoc code but can misread a data-looking first row.
Can I sort by more than one column in VBA?
Yes. One Sort call accepts up to three keys, Key1 through Key3, each with its own order. For more complex ordering, run successive sorts starting with the least important key.
Why did my column titles get sorted into the data?
Either Header was left out (the default is xlNo) or the range began below the header row. Include row 1 in the range and set Header:=xlYes.
Does sorting with VBA break formulas?
Formulas inside the sorted range move with their rows and keep pointing at the same relative cells. Formulas outside the range that refer into it still point at the same cell addresses, which may now hold a different record, so review cross-sheet references.
Can I undo a macro sort?
Not with Ctrl+Z in the normal way. Keep a backup copy or re-sort by an original identifier column if you need to restore the previous order.