Smart Systems for Home

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

Excel VBA Sort Table by Column: 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

To sort a table by a column in Excel VBA, use the Sort method on the table's Range, specifying the key column and order. The shortest working snippet is ActiveSheet.ListObjects("Table1").Range.Sort Key1:=Range("Table1[ColumnName]"), Order1:=xlAscending, Header:=xlYes. That single line sorts the whole table, keeps rows intact, and respects the header row. The steps below show how to set it up reliably, handle multiple keys, and avoid the mistakes that cause runtime errors or scrambled data.

What You'll Need

  • Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > check Developer, or Excel > Preferences > Ribbon & Toolbar on Mac).
  • A worksheet containing a real Excel Table (Insert > Table) with a header row. The table name appears in Table Design > Table Name; the default is something like Table1.
  • Basic familiarity with the VBA editor (Alt+F11 on Windows, Fn+Option+F11 on Mac).
  • Macro security set to allow macros in the workbook's location, or the file saved as .xlsm.

Menu labels and dialog wording can differ slightly by Excel version, platform and region. The VBA object model itself is consistent across recent versions, so the code below works on both Windows and Mac Excel.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Fn+Option+F11 (Mac). In the Project pane, find your workbook and insert a module via Insert > Module. Code in a standard module can be run manually or called from a button.
  2. Confirm the table name. Click any cell in the table and look at Table Design > Table Name. Use that exact name in the code. If you rename the table later, the code must be updated.
  3. Write the basic sort. Paste this into the module:
    Sub SortTableByColumn()
        Dim tbl As ListObject
        Set tbl = ActiveSheet.ListObjects("Table1")
        tbl.Range.Sort Key1:=tbl.ListColumns("Amount").Range, _
                       Order1:=xlAscending, _
                       Header:=xlYes
    End Sub
    Replace Table1 with your table name and Amount with the exact header text of the column you want to sort by. ListColumns("Amount").Range refers to the data cells under that header, which is what Key1 expects.
  4. Run the macro. Press F5 with the cursor inside the subroutine, or use Developer > Macros and pick SortTableByColumn. The table reorders immediately, and the header stays at the top because Header:=xlYes is set.
  5. Sort descending. Change Order1:=xlAscending to Order1:=xlDescending. Nothing else needs to change.
  6. Add a second sort key. Add Key2 and Order2 arguments. The first key is the primary sort; the second breaks ties:
    tbl.Range.Sort Key1:=tbl.ListColumns("Region").Range, _
                   Order1:=xlAscending, _
                   Key2:=tbl.ListColumns("Amount").Range, _
                   Order2:=xlDescending, _
                   Header:=xlYes
  7. Make it robust. Wrap the sort in error handling so a renamed table or column does not crash the macro:
    On Error GoTo CleanFail
    tbl.Range.Sort Key1:=tbl.ListColumns("Amount").Range, _
                   Order1:=xlAscending, Header:=xlYes
    Exit Sub
    CleanFail:
    MsgBox "Sort failed: check the table and column names."
    End Sub
  8. Save and test. Save the workbook as .xlsm. Test on a copy of the data first, especially if the table feeds formulas or pivot tables elsewhere.

Common Mistakes

  • Sorting the wrong range. Using ActiveSheet.Range("A1:D100") instead of the table's Range can leave rows misaligned if the range does not match the table exactly. Always sort tbl.Range.
  • Forgetting Header:=xlYes. Without it, VBA treats the header row as data and sorts it into the body, corrupting the table.
  • Using a column letter instead of the table column. Key1:=Range("C2") works only if that cell is inside the table and the table is active. tbl.ListColumns("Amount").Range is safer and survives column insertions.
  • Misspelling the table or header name. Both are case-sensitive in practice and must match exactly, including spaces. A trailing space in a header is a common culprit.
  • Sorting a filtered table. Sorting a table with active filters can produce unexpected visible order. Clear filters first if the result matters.
  • Assuming the macro sorts the whole sheet. It sorts only the table. Data outside the table is untouched, which is usually what you want but can surprise people.

Tips

  • Store the table name and column name in variables at the top of the macro so you change them in one place.
  • Use Application.ScreenUpdating = False before the sort and set it back to True afterward when sorting many tables in a loop; it speeds things up noticeably.
  • If you need to sort by a column whose header is not unique, refer to it by index instead: tbl.ListColumns(3).Range.
  • Assign the macro to a button (Developer > Insert > Button) so users can sort without opening the editor.
  • For date or text columns, the sort order follows Excel's normal rules, so dates stored as text will sort alphabetically, not chronologically. Convert them to real dates first.

Troubleshooting

Run-time error 9 (Subscript out of range). The table name does not exist on the active sheet. Check the sheet is the one you think it is and the name matches Table Design > Table Name exactly.

Run-time error 1004. Usually a bad key range or a header name that does not exist. Verify the column header text, including spaces and capitalization, and confirm Header:=xlYes is present.

Header row ends up in the middle. Header was omitted or set to xlNo. Add Header:=xlYes.

Nothing happens. The macro may be running on a different sheet than the one holding the table, or macros are disabled. Check the Trust Center macro settings and confirm the file is .xlsm.

Sort order looks wrong. The column may contain mixed data types (numbers stored as text). Select the column, use Data > Text to Columns or a conversion formula to fix the type, then re-run.

If that did not work, record a macro while sorting manually (Developer > Record Macro), then inspect the generated code. It shows the exact arguments Excel expects for your version and data.

Frequently Asked Questions

Can I sort a table without knowing its name?

Yes, if it is the only table on the sheet: ActiveSheet.ListObjects(1).Range.Sort .... This is fragile if a second table is added later, so naming the table is safer.

Does sorting a table with VBA break formulas?

No. Structured references and formulas inside the table move with their rows. Formulas outside the table that point at specific cells can break, so review those first.

How do I sort by multiple columns?

Add Key2, Key3 and matching Order arguments to the same Sort call, as shown in step 6. Excel supports up to 64 keys in the user interface; in VBA, a practical limit is far lower and two or three keys covers most needs.

Can I sort a table on a sheet that is not active?

Yes, if you reference the sheet explicitly: Worksheets("Data").ListObjects("Table1").Range.Sort .... Avoid ActiveSheet when the sheet may not be the one you expect.

Why does my date column sort alphabetically?

The dates are stored as text. Convert them to real date values (Data > Text to Columns, or CDate in VBA) and sort again.

Does this work in Excel for Mac?

Yes. The ListObject.Sort method and its arguments are the same. Only the keyboard shortcuts for opening the editor differ.