Excel VBA Sorting: Step-by-Step Guide
In this article
To sort data in Excel with VBA, use the Sort method on a Range object. The shortest working macro is Range("A1:C10").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes. This sorts the range A1:C10 by column A in ascending order, treating the first row as a header. You can extend this by adding Key2, Order2, and so on for multi-level sorts, or by using SortFields for more control. The steps below walk through creating a robust sorting macro from scratch.
What You'll Need
- Microsoft Excel (any recent version) with the Developer tab enabled. If you don't see the Developer tab, right-click the ribbon and choose Customize the Ribbon, then check Developer.
- Basic familiarity with the VBA editor (VBE). You can open it with Alt+F11.
- Data arranged in a contiguous range or table, with clear headers if you plan to use
Header:=xlYes.
Step-by-Step
- Open the VBA editor. Press Alt+F11 (or go to Developer > Visual Basic). In the Project Explorer, find your workbook and insert a new module: Insert > Module.
- Write a basic sort macro. In the module, type:
Sub SortBasic()
Range("A1:C10").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
End Sub
This sorts the range A1:C10 by column A ascending, assuming row 1 contains headers. Adjust the range to match your data. - Run the macro. Press F5 while the cursor is inside the subroutine, or go back to Excel and assign the macro to a button. Check that the data sorted correctly.
- Add a second sort key. To sort by column A then by column B, use:
Range("A1:C10").Sort Key1:=Range("A1"), Order1:=xlAscending, _
Key2:=Range("B1"), Order2:=xlDescending, Header:=xlYes
This sorts primarily by column A ascending, then by column B descending. - Use SortFields for more than three keys. The
Sortmethod only accepts up to three keys via Key1-Key3. For more, use theSortFieldscollection:With ActiveSheet.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A1"), Order:=xlAscending
.SortFields.Add Key:=Range("B1"), Order:=xlDescending
.SortFields.Add Key:=Range("C1"), Order:=xlAscending
.SetRange Range("A1:C10")
.Header = xlYes
.Apply
End With
This sorts by three columns with mixed orders. You can add moreSortFields.Addlines as needed. - Sort a table by column name. If your data is in a ListObject (Excel table), you can sort by column header name:
ActiveSheet.ListObjects("Table1").Sort.SortFields.Clear
ActiveSheet.ListObjects("Table1").Sort.SortFields.Add _
Key:=Range("Table1[Column1]"), Order:=xlAscending
With ActiveSheet.ListObjects("Table1").Sort
.Header = xlYes
.Apply
End With
Replace "Table1" and "Column1" with your table and column names. - Handle dynamic ranges. Instead of hard-coding A1:C10, use
CurrentRegionorUsedRangeto sort all contiguous data:Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
This sorts the entire block around A1. Be careful:CurrentRegionincludes all adjacent cells, so ensure no blank rows or columns separate your data. - Sort without headers. If your data has no header row, set
Header:=xlNoand useKey1:=Range("A1")to sort by the first column. The entire range, including the first row, will be sorted. - Sort by cell color or font color. Use
SortOn:=xlSortOnCellColorand specifyColororFontColor. Example:Range("A1:C10").Sort Key1:=Range("A1"), SortOn:=xlSortOnCellColor, _
Order1:=xlAscending, Header:=xlYes
This sorts by the background color of column A. You can also usexlSortOnFontColorfor font color. - Sort by custom list. To sort by a custom list (e.g., days of the week), use
CustomOrder:Range("A1:C10").Sort Key1:=Range("A1"), Order1:=xlAscending, _
CustomOrder:="Monday,Tuesday,Wednesday,Thursday,Friday", Header:=xlYes
The list must be comma-separated. This sorts column A according to the custom sequence. - Test and refine. Run the macro on a copy of your data first. Check that the sort order and range are correct. Adjust the range references or add error handling as needed.
Common Mistakes
- Forgetting to set Header. If you omit
Header, Excel may treat the first row as data and sort it into the middle. Always specifyHeader:=xlYesorxlNo. - Using the wrong range. If your range doesn't include all columns you want to sort together, you'll get misaligned data. Use
CurrentRegionor explicitly set the full range. - Not clearing SortFields. When using
SortFields, if you don't call.SortFields.Clearfirst, old sort keys may persist and cause unexpected results. - Assuming Key1-Key3 is unlimited. The
Sortmethod only accepts three keys. For more, useSortFields. - Sorting a filtered range. Sorting a range with hidden rows may include hidden data. Use
Sorton the visible range or remove filters first.
Tips
- Record a macro while sorting manually to see the generated VBA code. This is a great way to learn the syntax.
- Use
Application.ScreenUpdating = Falsebefore sorting and set it back toTrueafter to speed up macros on large datasets. - Store sort keys in variables if you need to change them dynamically.
- For tables, use the ListObject's Sort property to avoid range references that break when data changes.
- Always test on a copy of your data. Sorting cannot be undone with Ctrl+Z after the macro runs.
Troubleshooting
- Run-time error 1004: Sort method of Range class failed. This often means the range is not valid or the workbook is protected. Check that the sheet is not protected and the range exists.
- Headers get sorted as data. Ensure
Header:=xlYesis set and that your range includes the header row. - Sort order is wrong. Double-check the
Order1constant:xlAscendingorxlDescending. Also verify the Key range refers to the correct column. - Macro sorts only part of the data. Your range may not include all columns. Use
CurrentRegionor expand the range. - SortFields not working. Make sure you call
.Applyafter setting up the SortFields, and that.SetRangeis used to define the range.
Frequently Asked Questions
Can I sort by multiple columns with VBA?
Yes. Use Key1, Key2, and Key3 for up to three columns, or use the SortFields collection for more.
How do I sort a range that changes size?
Use Range("A1").CurrentRegion or UsedRange to refer to the entire data block dynamically.
Can I sort by cell color?
Yes. Set SortOn:=xlSortOnCellColor and specify the Order1 and optionally Color or FontColor.
Why does my macro sort the header row?
You likely omitted Header:=xlYes or set it to xlNo. Add or correct that argument.
Can I undo a VBA sort?
No, VBA actions are not added to the undo stack. Always keep a backup or work on a copy.
How do I sort a table by column name?
Use the ListObject's Sort property and reference the column by its header name in the Key argument, e.g., Range("Table1[Column1]").