Smart Systems for Home

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

Excel VBA Sort Range Multiple Columns: A Complete 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

Sorting a range by multiple columns in Excel VBA is achieved by using the Sort object within a worksheet, where you clear any existing sort fields and then add new SortFields for each column you wish to prioritize. This allows you to create a hierarchical sort—for example, sorting a list first by 'Last Name' and then by 'First Name' to ensure alphabetical order across a full dataset.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • A dataset with headers in the first row.
  • The Developer tab enabled in the Excel Ribbon (if not visible, right-click any tab, select Customize the Ribbon, and check the Developer box).
  • Basic familiarity with opening the Visual Basic Editor (VBE).

Step-by-Step

  1. Open the Visual Basic Editor: Press Alt + F11 on your keyboard. This opens the VBE window where all your macros are stored and written.
  2. Insert a New Module: In the top menu, go to Insert > Module. This creates a blank space where you can write your custom sorting procedure without affecting the specific code of a single sheet.
  3. Define the Worksheet and Range: Start your subroutine by defining which sheet and which range of cells you want to sort. It is best practice to use a variable for the worksheet to avoid errors if you have multiple sheets open. For example, Set ws = ThisWorkbook.Sheets("Sheet1") and Set myRange = ws.Range("A1:D100").
  4. Clear Existing Sort Fields: Before applying a new multi-column sort, you must clear any previous sorting rules applied to that range. Use the command ws.Sort.SortFields.Clear. If you skip this step, Excel may attempt to add your new rules on top of old ones, leading to unpredictable results or runtime errors.
  5. Add the Primary Sort Column: Use the .SortFields.Add method to define your first priority column. You need to specify the key (the range of the column), the sort order (ascending or descending), and the data type.
    Example: ws.Sort.SortFields.Add Key:=ws.Range("A2:A100"), SortOn:=xlSortOnValues, Order:=xlAscending. Note that the key range should exclude the header row (starting at row 2).
  6. Add Secondary and Tertiary Sort Columns: Repeat the .SortFields.Add command for every additional column you want to sort by. The order in which you write these lines in the code is the order of priority Excel will use. If you want to sort by Department (Col B) and then by Salary (Col C), add the Department key first and the Salary key second.
  7. Configure the Sort Settings: Now that the fields are defined, you must tell Excel how to handle the rest of the range. Use the ws.Sort object to set the following properties:
    • SetValues: Set ws.Sort.SetValues to True to ensure the sort is applied.
    • Header: Set ws.Sort.Header = xlYes if your range includes headers. This prevents your titles from being sorted into the data.
    • MatchCase: Set to False unless you need case-sensitive sorting.
  8. Apply the Sort: The final step is to call the .Apply method. Without this, the sort fields are defined in memory but not actually executed on the spreadsheet. Use ws.Sort.Apply.
  9. Run the Macro: Close the VBE window, return to Excel, press Alt + F8, select your macro name, and click Run.

Common Mistakes

One of the most frequent errors is forgetting to call SortFields.Clear. Because the Sort` object persists within the worksheet, adding new fields without clearing the old ones results in a "stack" of rules. If you previously sorted by Column C and then run a macro to sort by Column A and B, Excel may still be trying to apply the Column C rule at the end of the sequence, which can confuse the user when the data doesn't look exactly as expected.

Another common mistake is including the header row in the Key range. If your data is in A1:D100 and your header is in row 1, your key should be Range("A2:A100"). If you use Range("A1:A100") and set Header:=xlYes, Excel can sometimes become confused about where the data actually starts, potentially sorting your header row into the middle of your dataset.

Users also frequently confuse xlAscending and xlDescending. Remember that xlAscending is A-Z or 1-10, while xlDescending is Z-A or 10-1. When sorting multiple columns, it is common to want the first column ascending and the second descending (e.g., Sort by Category A-Z, then by Price High-to-Low). Ensure each .Add line has the correct Order parameter.

Tips

To make your code more robust, avoid hard-coding range addresses like "A1:D100". Instead, use dynamic ranges. You can find the last row of data using lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row. Then, define your range as ws.Range("A1:D" & lastRow). This ensures that your macro continues to work even as you add more rows of data to your sheet over time.

If you are working with very large datasets, you may notice the screen flickering as Excel rearranges the rows. You can stop this by adding Application.ScreenUpdating = False at the beginning of your macro and Application.ScreenUpdating = True at the end. This not only makes the process look professional but can also slightly increase the execution speed of the code.

Consider using a With...End With block to make your code cleaner. Instead of typing ws.Sort five times, you can wrap your logic in With ws.Sort. This reduces the amount of code you have to write and makes it easier for others to read and maintain.

Troubleshooting

If your code runs but the data does not move, the most likely culprit is the missing .Apply method. Many developers define the sort fields perfectly but forget that the Sort object requires an explicit command to execute the changes. Ensure ws.Sort.Apply is the final line of your sorting logic.

If you receive a Runtime Error 1004, check your range references. This error often occurs if the Key range does not match the size of the rest of the sort range. For example, if your total range is A1:D100, but your key is A2:A50, Excel will throw an error because the sort key must cover the same number of rows as the range being sorted.

If the sort is happening but the headers are being moved into the data, double-check your Header property. Ensure it is set to xlYes. If it is set to xlNo or xlGuess, Excel may treat your first row as a data entry and move it based on its alphabetical value.

If the data is sorting by the wrong columns, verify the column letters in your Key:=ws.Range(...) arguments. It is easy to accidentally put "B2:B100" when you meant "C2:C100", especially when dealing with many columns.

Frequently Asked Questions

Can I sort by more than three columns?

Yes, there is no practical limit to the number of sort levels you can add. You simply continue adding .SortFields.Add lines in the order of priority you require.

Does this method work for Excel Tables (ListObjects)?

While this method works for standard ranges, Excel Tables have their own Sort property. It is generally better to use ListObject.Sort for tables to maintain the table's structural integrity and ensure filtered views are updated.

Can I sort by a formula result?

Yes. As long as the formula results in a value (number, text, or date), the xlSortOnValues parameter will handle it correctly.

How do I sort in descending order for the second column only?

In your second .SortFields.Add line, simply change the Order parameter from xlAscending to xlDescending. The first column will remain ascending if its specific line is set to xlAscending.

Will this macro delete my data?

No, sorting only rearranges the existing rows; it does not delete or overwrite any cell values. However, it is always recommended to keep a backup of your data before running a new macro for the first time.