Smart Systems for Home

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

Excel VBA Sort by Column: 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 range by any column in Excel VBA with a single block of code: set a reference to the range, call its Sort method, point Key1 at the column you want, choose an order, and run it. The shortest working version is Range("A1:D20").Sort Key1:=Range("B1"), Order1:=xlAscending, Header:=xlYes. That sorts the whole block A1:D20 by column B, keeping each row intact. This guide shows how to make that reliable, how to sort by column number instead of a cell address, how to handle headers, multiple keys, and the mistakes that quietly corrupt data.

What You'll Need

  • Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > tick Developer, or Excel > Preferences > Ribbon & Toolbar on Mac).
  • A workbook saved as .xlsm if you want the macro to persist. Standard .xlsx files drop VBA code on save.
  • Your data in a contiguous block with a single header row, no blank rows or columns inside the block.
  • Basic comfort with the VBA editor (Alt+F11 on Windows, Option+F11 on Mac). Menu labels can differ slightly by version and region.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Option+F11 (Mac). In the Project pane, right-click your workbook and choose Insert > Module. A blank code window appears.
  2. Write a basic sort macro. Paste this and adjust the range to match your data:
    Sub SortByColumnB()
        Range("A1:D20").Sort _
            Key1:=Range("B1"), _
            Order1:=xlAscending, _
            Header:=xlYes
    End Sub
    The Key1 argument is the cell whose column you want to sort by. Because Header:=xlYes is set, Excel treats row 1 as a header and does not sort it into the data.
  3. Run it. Press F5 or click Run > Run Sub. The block reorders by column B, ascending.
  4. Sort by column number instead of a cell. If you do not want to hard-code a cell reference, use the Columns argument with a number relative to the range. For range A1:D20, column 2 is B:
    Range("A1:D20").Sort _
        Key1:=Range("A1:D20").Columns(2), _
        Order1:=xlAscending, _
        Header:=xlYes
    This is safer when columns get inserted, because you can compute the number from a header lookup instead of trusting a letter.
  5. Sort descending. Change Order1:=xlAscending to Order1:=xlDescending.
  6. Add a second sort key. Add Key2 and Order2 to break ties:
    Range("A1:D20").Sort _
        Key1:=Range("B1"), Order1:=xlAscending, _
        Key2:=Range("C1"), Order2:=xlDescending, _
        Header:=xlYes
    Rows are ordered by B first, then C within matching B values.
  7. Make the range dynamic. Replace the fixed address with Range("A1").CurrentRegion, which expands to the whole contiguous block around A1. That way added rows are included automatically. If your block has blank cells inside it, CurrentRegion will stop early, so clean the data first.
  8. Sort a whole table object. If the data is a ListObject, use ActiveSheet.ListObjects("Table1").Sort.SortFields and add a field with Key:=Range("Table1[[#Headers],[Amount]]"), then call .Apply. This is the more robust route for tables that grow.
  9. Save as .xlsm. File > Save As, choose Excel Macro-Enabled Workbook. Close and reopen to confirm the macro survives.

Common Mistakes

  • Sorting only one column. Range("B1:B20").Sort reorders B alone and detaches it from the rest of each row. Always sort the full block, not the key column.
  • Forgetting Header:=xlYes. Without it, Excel sorts the header text into the data, usually to the top or bottom.
  • Using the wrong column number. Columns(2) means the second column of the range, not column B of the sheet. If the range starts at C, Columns(2) is D.
  • Leaving blank rows in the block. Both a fixed range and CurrentRegion misbehave around gaps.
  • Assuming Key1 accepts a number. It needs a Range object, not a column index. Use Range("B1") or .Columns(2).
  • Saving as .xlsx. The code is discarded silently on save.

Tips

  • Turn off screen updating around the sort (Application.ScreenUpdating = False, then back to True) for a visible speed gain on large blocks.
  • Store the key column in a variable so you can change it in one place: Dim keyCol As Long: keyCol = 2.
  • Use xlGuess for Header only when you are unsure; xlYes or xlNo is predictable.
  • Sort on a helper column if you need custom order (for example, priority High/Medium/Low). Build a numeric rank in an unused column, sort by that, then delete it.
  • Record a macro with the Macro Recorder while sorting manually once; the generated code shows the exact arguments your Excel version expects.

Troubleshooting

If the macro does nothing, check that the sheet referenced is the active one, or qualify the range with a worksheet object such as Worksheets("Data").Range(...). Macros run against the active sheet by default.

If you get a "Sort method of Range class failed" error, the range is usually malformed, contains merged cells, or overlaps a protected sheet. Unmerge cells and unprotect the sheet first.

If the header ends up in the data, set Header:=xlYes explicitly and confirm the header row is the first row of the range.

If rows look scrambled, you probably sorted a single column. Undo immediately (Ctrl+Z) and re-sort the full block.

If the code is gone after reopening, the file was saved as .xlsx. Save as .xlsm and re-add the module.

If sorting is slow on thousands of rows, disable screen updating and calculation, sort once, then re-enable both.

Frequently Asked Questions

Can I sort by a column without knowing its letter?

Yes. Use Range("A1:D20").Columns(n) where n is the position within the range, or look up the header text with Match and pass that number.

Does VBA sorting keep rows together?

It does when you sort the entire data block. Sorting a single column breaks the row association.

Can I sort by more than two columns?

Yes. The Sort method supports Key1 through Key3, plus Order1 to Order3. For more levels, sort in reverse priority order or use a helper rank column.

Will this work on Excel for Mac?

Yes, the Range.Sort method and its arguments are the same. The keyboard shortcut to open the editor differs (Option+F11).

How do I sort a table that grows every week?

Use Range("A1").CurrentRegion or a ListObject's Sort method, both of which expand with the data as long as there are no blank rows inside the block.

Can I undo a VBA sort?

Only with Ctrl+Z immediately after running it, and only if the macro did not clear the undo stack. For important data, copy the sheet before sorting.