Smart Systems for Home

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

Excel VBA Sort by Multiple Columns: 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

You can sort a worksheet by multiple columns in Excel VBA using the Sort method with a SortFields collection: clear any existing sort fields, add one field per column with its key, sort order and optional custom order, then apply the sort to a defined range. The code below works in Excel 2010 and later on Windows and Mac; exact dialog labels in the Excel interface can differ slightly by version and region, but the VBA object model is stable.

What You'll Need

  • Excel 2010 or later (Windows or Mac) with the Developer tab enabled: File > Options > Customize Ribbon > Main Tabs > check Developer. On Mac, Excel > Preferences > Ribbon & Toolbar.
  • A worksheet with a clean data range: one header row, no blank rows or columns inside the data, and no merged cells.
  • Basic familiarity with the Visual Basic Editor (VBE): press Alt+F11 on Windows, or Fn+Option+F11 on Mac, to open it.
  • A saved copy of your workbook before running any macro that rearranges data.

Step-by-Step

  1. Open the Visual Basic Editor and insert a module. Press Alt+F11 (Windows) or Fn+Option+F11 (Mac). In the Project Explorer, right-click your workbook, choose Insert > Module. A blank code window appears.
  2. Write a macro that defines the range. Use Range or CurrentRegion to capture the data including headers. For example:
    Sub SortMulti()
        Dim ws As Worksheet
        Dim rng As Range
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        Set rng = ws.Range("A1").CurrentRegion
    
    Replace "Sheet1" with your sheet name. CurrentRegion expands to the contiguous block around A1; if your data has gaps, set an explicit range such as ws.Range("A1:E200").
  3. Clear any existing sort fields. Add rng.Sort.SortFields.Clear before adding new fields. Without this, Excel may retain old sort criteria and throw an error or produce an unexpected order.
  4. Add the first sort field. Use rng.Sort.SortFields.Add Key:=rng.Columns(1), Order:=xlAscending. The Key argument is a range that must be a single column within the sort range. Order accepts xlAscending or xlDescending.
  5. Add additional fields in priority order. Each subsequent Add call becomes a lower-priority sort key:
        rng.Sort.SortFields.Add Key:=rng.Columns(2), Order:=xlAscending
        rng.Sort.SortFields.Add Key:=rng.Columns(3), Order:=xlDescending
    
    The first field added is the primary sort; later fields break ties.
  6. Apply the sort. Call the Sort method with Header:=xlYes so the first row is treated as headers and not sorted into the data:
        With rng.Sort
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .Apply
        End With
    End Sub
    
    MatchCase controls whether uppercase and lowercase are treated as equal; Orientation sets top-to-bottom (rows) versus left-to-right (columns).
  7. Run the macro. Press F5 in the VBE, or return to Excel and use Developer > Macros, select SortMulti, and click Run. Your data should now be sorted by the columns you specified, in the order you added them.
  8. Verify and adjust. Check that headers stayed in row 1 and that ties are broken as expected. If not, review the order of your Add calls and confirm each Key refers to a column inside rng.

Common Mistakes

  • Forgetting to clear sort fields. Reusing a range that already has sort criteria can cause run-time error 1004 or unexpected results. Always call SortFields.Clear first.
  • Using a Key outside the sort range. If rng is A1:C100, a Key of column D will fail. Make sure every Key column is inside the range.
  • Omitting Header:=xlYes. Without it, Excel may sort the header row into the data, corrupting the order and misaligning column meanings.
  • Assuming the first Add is the primary key. The order of Add calls defines priority: first added is primary. Adding fields in the wrong order gives the wrong grouping.
  • Sorting a range with blank rows or merged cells. Blank rows split the data; merged cells prevent a clean sort. Remove them or sort each contiguous block separately.
  • Hard-coding sheet names. If the sheet is renamed, the macro fails. Use the sheet's code name or prompt the user, or reference ActiveSheet if appropriate.

Tips

  • Use rng.Columns(n) rather than absolute addresses like Range("B1") so the macro keeps working if you insert columns later.
  • For custom lists (e.g., Low, Medium, High), set Order:=xlAscending and add CustomOrder:= with a comma-separated string, or use OrderCustom with the list index.
  • To sort left-to-right (columns instead of rows), set Orientation:=xlLeftToRight and use row-based keys.
  • Store the sort configuration in variables so you can reuse the same macro for different sheets or ranges.
  • Test on a copy first. Sorting is destructive to row order; keep a backup until the macro is verified.

Troubleshooting

  • Run-time error 1004 "The sort reference is not valid". Usually a Key outside the range, a range with no data, or a missing header setting. Check that rng includes all Key columns and that Header is set.
  • Headers got sorted into the data. Add or correct .Header = xlYes. If the header row contains blanks, Excel may not detect it; fill in header labels or use an explicit range that excludes the header and set Header:=xlNo.
  • Sort order is wrong despite correct code. Confirm the order of Add calls. Also check for leftover sort fields from a previous run; clear them.
  • Macro runs but nothing changes. Ensure .Apply is called and that the worksheet is not protected. Unprotect the sheet or run the macro on an unprotected copy.
  • Data appears misaligned after sorting. This often means the range included only part of the table. Expand rng to cover all columns, or use a named range that covers the full table.

Frequently Asked Questions

Can I sort by more than three columns?

Yes. The SortFields collection accepts many fields; add as many as you need. The practical limit is the number of columns in your range.

How do I sort a table (ListObject) instead of a plain range?

Use the table's Sort property: ActiveSheet.ListObjects("Table1").Sort.SortFields.Add with the same Key, Order and Header arguments, then call .Apply.

Does this work on Excel for Mac?

Yes, the VBA sort object model is the same on Mac. Use Fn+Option+F11 to open the VBE. Some older Mac versions may have minor UI differences, but the code runs unchanged.

Can I sort by cell color or font color?

Yes. Use SortOn:=xlSortOnCellColor or xlSortOnFontColor and set SortOnValue.Color to the desired color. This is useful for flagging rows before sorting.

Why does my macro sort only part of the data?

Your range likely stops short. Check that rng covers every column and row of the table. CurrentRegion stops at blank rows or columns, so remove gaps or set an explicit range.

Can I undo a VBA sort?

Not with Ctrl+Z after the macro runs. Save a backup before running, or have the macro copy the original range to a hidden sheet first so you can restore it.