Smart Systems for Home

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

Excel VBA Sort Apply: How to Sort Data with VBA Code

· 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

Applying a sort in Excel VBA allows you to automate the organization of large datasets based on specific criteria, ensuring your reports remain consistent without manual intervention. To apply a sort via VBA, you primarily use the .Sort method of the Range object or the Sort object within a Worksheet, defining the key (the column to sort by), the order (ascending or descending), and the range of data to be affected.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • A dataset with headers (column names) to ensure the sort does not move your titles.
  • The Developer tab enabled in the Excel Ribbon to access the Visual Basic Editor (VBE).
  • Basic familiarity with how to open a module in VBA.

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 written.
  2. Insert a New Module: In the top menu, go to Insert > Module. This creates a blank space where you can write your sorting procedure.
  3. Define the Worksheet and Range: Start your subroutine by declaring the worksheet and the specific range you want to sort. It is best practice to define these as variables to make the code easier to read and maintain. For example, set a variable for the sheet name and another for the data range (e.g., A1:D100).
  4. Clear Previous Sort Settings: Before applying a new sort, it is critical to clear any existing sort parameters. Use ActiveSheet.Sort.SortFields.Clear. If you skip this step, Excel may attempt to add your new sort criteria on top of old ones, leading to unpredictable results or errors.
  5. Add the Sort Key: Use the .SortFields.Add method to tell Excel which column determines the order. You must specify the Key (the range of the column being sorted), the SortOn property (usually xlSortOnValues), and the Order (xlAscending or xlDescending).
  6. Configure the Sort Object: Once the key is added, you must apply the sort to the worksheet. Set Set mySort = ActiveSheet.Sort. Then, configure the following properties:
    • SetRng: This is the entire block of data including all columns that should move together.
    • Header: Set this to xlYes if your data has a header row, or xlNo if it does not. This prevents your column titles from being sorted into the middle of your data.
    • MatchCase: Set to False unless you need a case-sensitive sort.
  7. Execute the Sort: The final and most important step is to call the .Apply method. Without mySort.Apply, the settings are stored in memory but the actual cells on the spreadsheet will not move.
  8. Test the Macro: Return to your Excel sheet, press Alt + F8, select your macro name, and click Run to verify the data sorts as expected.

Common Mistakes

One of the most frequent errors is forgetting to call .SortFields.Clear. Because the Sort object is persistent within a worksheet, adding a new sort key without clearing the old ones creates a multi-level sort. For example, if you sorted by "Date" yesterday and "Name" today, the code will first sort by Date and then by Name, which might not be what you intended.

Another common mistake is incorrectly defining the SetRng. Users often set the range to only the column they are sorting. If you do this, Excel will only move the values in that one column, effectively disconnecting that data from the rest of the row. This ruins the integrity of your database. Always ensure the SetRng encompasses every column that belongs to the record.

Misidentifying the header status is also a recurring issue. If you set Header := xlNo when you actually have headers, your top row (e.g., "First Name", "Date", "Amount") will be treated as data and sorted alphabetically, often ending up in the middle of the list.

Tips

To make your code more dynamic, avoid hard-coding ranges like "A1:D100". Instead, use CurrentRegion. For example, Range("A1").CurrentRegion will automatically detect the entire block of connected data, meaning your macro will still work even if you add more rows or columns to your table in the future.

If you need to sort by multiple levels (e.g., sort by Department first, then by Last Name), simply repeat the .SortFields.Add line for each level of sorting before calling the .Apply method. The order in which you add the fields determines the priority of the sort.

For better performance on very large datasets, consider turning off screen updating at the start of your macro using Application.ScreenUpdating = False and turning it back on at the end. This prevents Excel from visually refreshing the screen every time a row moves, which significantly speeds up the execution time.

Troubleshooting

If your code runs without an error but the data does not move, double-check that you included the .Apply command. This is the most common reason for "silent failure" in VBA sorting.

If you receive a "Run-time error 1004", check for merged cells. Excel's sorting engine cannot handle ranges that contain merged cells of different sizes. Unmerge all cells within your sort range and try again. If merged cells are necessary for formatting, consider using "Center Across Selection" in the Format Cells alignment menu instead.

If the sort is producing strange results, check for trailing spaces in your data. A cell containing "Apple " (with a space) will be sorted differently than "Apple". Use the TRIM function in Excel or a VBA loop to clean your data before applying the sort.

If the macro crashes when the sheet is protected, you must unprotect the sheet at the beginning of the code using ActiveSheet.Unprotect "YourPassword" and reprotect it at the end using ActiveSheet.Protect "YourPassword". VBA cannot modify the structure or order of cells on a protected worksheet.

Frequently Asked Questions

Can I sort data in descending order?

Yes. In the .SortFields.Add method, change the Order parameter from xlAscending to xlDescending.

How do I sort by a column that isn't the first column?

You specify the column in the Key argument. For example, to sort by column C, set the key to Range("C1") or Columns("C").

Will VBA sorting delete any of my data?

No, sorting only rearranges the order of existing rows. It does not delete or modify the content of the cells.

Can I sort based on a formula result?

Yes, as long as the formula returns a value (number, text, or date), the xlSortOnValues property will work correctly.

Does this work on Excel Tables (ListObjects)?

While the standard Range sort works, Tables have their own ListObject.Sort method which is often more efficient for structured data.