Smart Systems for Home

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

Excel VBA Sorting: Step-by-Step Guide

· 5 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

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Use SortFields for more than three keys. The Sort method only accepts up to three keys via Key1-Key3. For more, use the SortFields collection:
    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 more SortFields.Add lines as needed.
  6. 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.
  7. Handle dynamic ranges. Instead of hard-coding A1:C10, use CurrentRegion or UsedRange to sort all contiguous data:
    Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
    This sorts the entire block around A1. Be careful: CurrentRegion includes all adjacent cells, so ensure no blank rows or columns separate your data.
  8. Sort without headers. If your data has no header row, set Header:=xlNo and use Key1:=Range("A1") to sort by the first column. The entire range, including the first row, will be sorted.
  9. Sort by cell color or font color. Use SortOn:=xlSortOnCellColor and specify Color or FontColor. 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 use xlSortOnFontColor for font color.
  10. 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.
  11. 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 specify Header:=xlYes or xlNo.
  • Using the wrong range. If your range doesn't include all columns you want to sort together, you'll get misaligned data. Use CurrentRegion or explicitly set the full range.
  • Not clearing SortFields. When using SortFields, if you don't call .SortFields.Clear first, old sort keys may persist and cause unexpected results.
  • Assuming Key1-Key3 is unlimited. The Sort method only accepts three keys. For more, use SortFields.
  • Sorting a filtered range. Sorting a range with hidden rows may include hidden data. Use Sort on 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 = False before sorting and set it back to True after 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:=xlYes is set and that your range includes the header row.
  • Sort order is wrong. Double-check the Order1 constant: xlAscending or xlDescending. 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 CurrentRegion or expand the range.
  • SortFields not working. Make sure you call .Apply after setting up the SortFields, and that .SetRange is 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]").