Smart Systems for Home

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

Excel VBA Sort Data: 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

You sort data in Excel VBA with the Range.Sort method, and the shortest working version is Range("A1:C100").Sort Key1:=Range("A2"), Order1:=xlAscending, Header:=xlYes. That one line orders rows A1:C100 by the values in column A, keeps the header out of the sort, and moves each whole row together so records stay intact. The rest of this guide is about getting that line to behave: choosing the right range, adding a second sort key, safely handling blanks and headers, and fixing the errors that appear when your range is wrong.

A quick note before the steps: Excel's menu names and dialog labels vary slightly by version, language and platform, and the same is true of some object names in the macro recorder. The VBA constants below are stable across modern Excel for Windows and Mac, but if a recorded macro uses different wording, trust the recorder's output for your own copy of Excel.

What You'll Need

  • Excel for Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > tick Developer on Windows; on Mac, Excel > Preferences > Ribbon & Toolbar).
  • A workbook saved as .xlsm or .xlsb if you want to keep the macro. A plain .xlsx will strip VBA when you save.
  • A data table with one header row and no blank rows or columns inside it. Blanks split the range and cause partial sorts.
  • Optional but useful: the Macro Recorder, so you can record a manual sort once and read the exact code Excel produces.

Step-by-Step

  1. Back up first. Sorting is destructive to row order and cannot be undone once the workbook is saved. Keep a copy or work on a copy sheet before you run any sort macro.
  2. Open the editor. Press Alt+F11 on Windows (Fn+Option+F11 on many Macs) to open the Visual Basic Editor, then use Insert > Module to add a blank module.
  3. Write a simple macro shell. Type Sub SortData() and End Sub. Everything else goes between the two lines.
  4. Point at the right worksheet. Always qualify the sheet, for example Worksheets("Data"), rather than relying on whichever sheet is active. Relying on ActiveSheet is the most common reason a macro sorts the wrong data when a user clicks a different tab.
  5. Define the range. A fixed range like Range("A1:D200") is fine for stable data. For growing tables, use Range("A1").CurrentRegion, which expands to the surrounding block of cells and stops at blank rows and columns.
  6. Add the Key1 argument. Key1 is the column you sort by. You can pass a cell, Key1:=Range("B2"), or a column number inside the range, Key1:=Range("A1:D200").Columns(2). Both mean the second column of the range.
  7. Set the order. Use Order1:=xlAscending for A to Z and smallest to largest, or Order1:=xlDescending for the reverse.
  8. Declare the header. Set Header:=xlYes when the first row contains column titles. Excel then excludes it from the sort. Use xlNo if your range has no header, otherwise the header row gets sorted into the data.
  9. Run the complete line. A working example: Worksheets("Data").Range("A1").CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlYes. Note that with CurrentRegion the key cell should sit in the same sheet as the range.
  10. Add a second key for ties. Extend the same statement with Key2 and Order2: ..., Key1:=Range("B2"), Order1:=xlAscending, Key2:=Range("C2"), Order2:=xlDescending, Header:=xlYes. Rows that tie on the first column are then ordered by the second.
  11. Sort dates and numbers correctly. Excel decides the sort type from the cell contents. If a date column is stored as text, xlAscending sorts it alphabetically and January may land after December. Store dates as real dates, or convert with CDate before sorting.
  12. Run it. Press F5 inside the editor, or assign the macro to a button via Developer > Insert > Button (Form Control) so colleagues can use it without opening the editor.
  13. Check the result. Confirm the header is still on top, no rows were orphaned, and the row count matches the original. If the count dropped, a blank row inside your data split the range.

Common Mistakes

  • Sorting only one column. If the range covers just column B, Excel shuffles those cells while columns A and C stay put, and your records no longer line up. Always select the whole table.
  • Forgetting Header:=xlYes. The default for Header is xlNo, so the header falls into the sort and appears in the middle of the data or at the bottom.
  • Using ActiveSheet. Macros that depend on the active sheet break the moment someone clicks another tab. Name the sheet explicitly.
  • Leaving blank rows or columns in the table. CurrentRegion stops at the first gap, so a single empty row silently halves the range being sorted.
  • Sorting with merged cells. Merged cells inside the range cause "This operation requires the merged cells to be identically sized", and sorting will refuse to run.
  • Double-clicking Key cells. The Key must be a single cell or a column reference, not a whole multi-cell range, or you get a type mismatch.

Tips

  • Record a manual sort with the Macro Recorder once. The generated code shows you the exact arguments your version expects, including any you did not think of.
  • Sort by a helper column when the real order is custom, such as priority levels or weekdays. Build the sortable value first, sort, then delete the helper.
  • Turn off Application.ScreenUpdating = False before a sort and back to True afterwards on large tables. It speeds things up and hides the flicker.
  • Store the original order in a numbered column before sorting, so you can restore it by sorting that column ascending.
  • Keep sort keys in cells near the data rather than hard-coded, so a user can change the sort column without editing code.

Troubleshooting

If nothing appears to happen, check that the macro actually ran on the sheet you expect and that the range is not empty. Confirm the sheet name in code matches the tab exactly, including spaces, which need Worksheets("Sales Data") with the spaces inside quotes.

If you get "Run-time error 1004: Sort method of Range class failed", the usual causes are a protected sheet, merged cells in the range, or a key cell outside the range being sorted. Unprotect the sheet, unmerge cells, and make sure every Key cell sits inside the range. The same error appears if the workbook is shared, because sorting is blocked while shared; unshare it from the Review tab first.

If the header row ends up sorted into the data, add Header:=xlYes. If the first data row vanished, the opposite happened: your data has no header and you told Excel it did. If only part of the table moved, your range was too small or a blank row cut it short, so reference the full table or use CurrentRegion.

If dates sort oddly, format the column as Date and re-enter the values, or check with IsDate in a quick test macro. If numbers sort as text, look for cells with a leading apostrophe or left-aligned values.

Frequently Asked Questions

Can I sort without changing the workbook open on screen?

Yes. Reference the worksheet by name and, if needed, open the file with Workbooks.Open and close it after saving, so the sort runs in the background.

How do I sort by more than two columns?

Add Key3, Order3 and further arguments to the same Sort statement. Excel supports up to 64 sort levels per sort operation.

Does Range.Sort work the same on Mac?

The method and constants are the same. The keyboard shortcuts for the editor differ, and some older Mac versions have quirks with CurrentRegion, so test on your own build.

How do I undo a sort run by a macro?

Ctrl+Z usually reverses the last action in the session, but it is unreliable after code runs. Saving a copy beforehand, or keeping a sequence number column, is the dependable option.

Can I sort a table object instead of a range?

Yes. A ListObject has its own Sort object, which automatically knows the table's extent and headers, and is safer for structured tables that grow.