Excel VBA Sort Sheet by Column: Step-by-Step Guide
In this article
You can sort a sheet by a column in Excel VBA using the Sort method on a Range object, or by calling Sort on the sheet's used range. The shortest working pattern is to set the range, choose the key column, and call Apply. For example: ActiveSheet.Sort.SortFields.Add Key:=Range("B2:B100"), Order:=xlAscending followed by ActiveSheet.Sort.SetRange Range("A1:D100") and ActiveSheet.Sort.Apply. This guide shows the full, reliable version with headers, error handling, and the mistakes that cause runtime errors.
What You'll Need
- Excel with the Developer tab enabled (File > Options > Customize Ribbon > check Developer).
- A worksheet with data arranged in columns, ideally with a header row.
- Basic familiarity with opening the VBA editor (Alt+F11) and inserting a module.
- Macro-enabled workbook saved as .xlsm if you want to keep the code.
Step-by-Step
- Open the VBA editor. Press Alt+F11. In the Project pane, right-click your workbook, choose Insert > Module. A blank code window opens.
- Write a macro skeleton. Start with
Sub SortByColumn()and end withEnd Sub. Declare a worksheet variable:Dim ws As WorksheetandSet ws = ActiveSheet. Using a variable makes the code easier to adapt. - Define the range to sort. Use
ws.Range("A1:D100")for a fixed range, orws.UsedRangefor the whole used area. Include the header row in the range but tell Excel it has headers in the next step. - Clear any previous sort state. Call
ws.Sort.SortFields.Clearbefore adding fields. If you skip this, Excel may raise error 1004 because old sort fields persist. - Add the sort key. Use
ws.Sort.SortFields.Add Key:=ws.Range("B2"), Order:=xlAscending. The key can be a single cell in the column you want to sort by; Excel expands it to the column. For descending, usexlDescending. - Set the range and header flag. Write
With ws.Sort, then.SetRange ws.Range("A1:D100")and.Header = xlYes. If your data has no header, usexlNo. Close withEnd With. - Apply the sort. Call
ws.Sort.Apply. The sheet reorders immediately. If you want to sort a copy, copy the range to a new sheet first and run the same code on that sheet. - Add error handling. Wrap the sort in
On Error GoTo CleanFailand aCleanFail:label that shows a message box withErr.Description. This prevents silent failures when the range is empty or protected. - Run and test. Press F5 or run the macro from Developer > Macros. Check that headers stayed in row 1 and that the chosen column is ordered correctly. Undo with Ctrl+Z does not reverse a VBA sort, so test on a copy first.
Common Mistakes
Forgetting to clear SortFields. Reusing a sheet's Sort object without clearing fields causes runtime error 1004. Always call SortFields.Clear first.
Sorting only one column. If you set the range to a single column, adjacent data does not move with it and rows become mismatched. Always set the full table range in SetRange.
Wrong header setting. Setting Header = xlYes when there is no header sorts the first data row into the header position. Match the flag to your actual layout.
Using ActiveSheet blindly. If the wrong sheet is active, the macro sorts the wrong data. Refer to sheets by name, for example ThisWorkbook.Worksheets("Data").
Protected sheets. Sorting a protected sheet fails unless the code unprotects it first. Unprotect, sort, then reprotect, and store the password securely rather than hard-coding it in the module.
Tips
Sort by multiple columns by adding more SortFields.Add lines before Apply. The order you add them sets the priority. Use Order:=xlAscending on the first key and a second key for tie-breaking.
For text that should sort like dates or numbers, set SortOn:=xlSortOnValues and, if needed, DataOption:=xlSortNormal. Avoid xlSortOnCellColor unless you have set a cell color.
To sort by column position rather than letter, use Key:=ws.Cells(2, 3) for column C. This is useful when columns shift.
Record a macro with the Macro Recorder while sorting manually, then read the generated code. It shows the exact property names Excel expects for your version.
Keep the sort range dynamic with ws.Range("A1").CurrentRegion. It expands to the contiguous block around A1 and avoids hard-coded row counts.
Troubleshooting
Error 1004 “Sort method of Range class failed”. Usually caused by missing SortFields.Clear, a range that includes merged cells, or a protected sheet. Unmerge cells, clear fields, and unprotect before retrying.
Headers move into the data. Change Header to xlNo or adjust the range to start at the first data row.
Only one column reorders. Your SetRange is narrower than the table. Widen it to cover all columns.
Nothing happens. Check that the macro actually ran (add a MsgBox at the end), that the sheet name is correct, and that the range is not empty.
Sort order looks wrong for numbers stored as text. Convert the column to real numbers, or use a helper column with VALUE() and sort on that.
Macro disabled. Enable macros in the Trust Center, or the workbook opens with code blocked and the sort never runs.
Frequently Asked Questions
Can I sort without selecting the sheet first?
Yes. Refer to the worksheet object directly, for example ThisWorkbook.Worksheets("Data").Sort, so the active sheet does not matter.
How do I sort descending?
Change Order:=xlAscending to Order:=xlDescending on the sort field.
Does VBA sort support multiple keys?
Yes. Add several SortFields.Add lines before Apply; the first added is the primary key.
Why does my macro fail on a protected sheet?
Sorting changes cells, which protection blocks. Unprotect the sheet in code, sort, then protect it again.
Can I undo a VBA sort?
No. Ctrl+Z does not reverse a macro-driven sort. Keep a backup copy or sort a duplicate range if you may need the original order.
What range should I use for a growing table?
Use ws.Range("A1").CurrentRegion so the range expands with the data, or convert the data to an Excel Table and sort the table's range.