To perform a custom sort in Excel VBA, you must define a custom list using the Application.AddCustomList method or utilize the Sort` object's CustomOrder property. This allows you to arrange data based on a non-alphabetical sequence, such as "Low, Medium, High" or "Monday, Tuesday, Wednesday," rather than the standard A-Z or numerical order. By specifying a comma-separated string of values in your code, you tell Excel exactly which order the data should follow regardless of the characters' natural sorting logic.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac PC.
  • A dataset that requires a specific, non-standard order (e.g., priority levels, sizes, or custom categories).
  • The Developer tab enabled in the Excel Ribbon to access the Visual Basic Editor.
  • Basic familiarity with how to open a VBA module.

Step-by-Step

  1. Enable the Developer Tab: If you do not see the Developer tab in your ribbon, right-click any existing tab, select "Customize the Ribbon," and check the box for "Developer" in the right-hand column. Click OK.
  2. Open the Visual Basic Editor: Click the "Developer" tab and then click the "Visual Basic" button (or press Alt + F11 on your keyboard).
  3. Insert a New Module: In the Project Explorer window on the left, right-click your workbook name, hover over "Insert," and select "Module." This creates a blank space where your custom sort script will live.
  4. Define Your Custom Order String: Decide on the exact sequence you want. For example, if you are sorting by priority, your string should be "Low,Medium,High". Note that these must match the text in your cells exactly, including capitalization and spacing.
  5. Write the Sort Code: Copy and paste the following logic into your module. In this example, we assume your data is in columns A through C and you are sorting by column A.
  6. Sub CustomSortData()
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
        
        Dim customOrder As String
        customOrder = "Low,Medium,High"
        
        Dim sortRange As Range
        Set sortRange = ws.Range("A1:C100")
        
        With ws.Sort
            .SortFields.Clear
            .SortFields.Add Key:=ws.Range("A1"), _n    SortOn:=xlSortOnValues, _n    Order:=xlAscending, _n    CustomOrder:=customOrder, _n    DataOption:=xlSortNormal
            .SetRange sortRange
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End Sub
  7. Adjust the Ranges: Change "Sheet1" to the actual name of your worksheet. Change "A1:C100" to match the full extent of your data table. Change "A1" to the top cell of the column you wish to sort by.
  8. Run the Macro: You can run the code by pressing F5 while the cursor is inside the subroutine, or by returning to the Excel sheet, clicking "Macros" on the Developer tab, selecting "CustomSortData," and clicking "Run."
  9. Verify the Results: Check your data to ensure that "Low" appears first, followed by "Medium," and then "High," regardless of the fact that "High" comes alphabetically before "Low."

Common Mistakes

One of the most frequent errors is a mismatch between the custom order string and the actual cell data. If your cells contain "Low " (with a trailing space) but your VBA string is "Low", Excel will treat the cell value as an unknown item and place it at the bottom of the sorted list. Always ensure there are no hidden spaces in your source data.

Another common mistake is forgetting to use .SortFields.Clear. The Excel Sort object remembers previous sort settings. If you run a standard sort and then run a custom sort without clearing the fields, Excel may attempt to perform a multi-level sort, leading to unexpected results or the custom sort being ignored entirely.

Users often forget to define the .Header property. If your data has headers but you set .Header = xlNo, Excel will treat your column titles as data and sort them into the list based on the custom order. Conversely, setting xlYes when there are no headers will result in the first row of your actual data being frozen at the top and excluded from the sort.

Defining the Key range incorrectly is also a recurring issue. The Key should be a single cell or a range within the column you are sorting. If you provide a range that spans multiple columns, the VBA engine may throw a runtime error or produce an inconsistent sort.

Tips

For dynamic lists, instead of hard-coding the custom order string like "Low,Medium,High", you can store your desired order in a hidden worksheet. You can then use a VBA loop to join those cells into a single comma-separated string. This allows non-technical users to change the sort order by simply editing the hidden list without touching the VBA code.

If you find yourself using the same custom sort across multiple workbooks, consider adding the list to the global Excel application using Application.AddCustomList. This makes the list available in the standard Excel "Custom Sort" dialog box for all files, not just the one containing the macro.

To improve performance on very large datasets, turn off screen updating and automatic calculations at the start of your macro using Application.ScreenUpdating = False and Application.Calculation = xlCalculationManual. Remember to set them back to True and xlCalculationAutomatic at the end of the script to ensure the UI remains responsive.

When dealing with case sensitivity, the .MatchCase property is vital. If your data is inconsistent (e.g., "low", "Low", "LOW"), setting .MatchCase = False ensures that all variations are treated as the same value and sorted according to your custom list.

Troubleshooting

If the data does not sort in the custom order and instead defaults to A-Z, first check that the CustomOrder parameter is actually being passed. Use Debug.Print customOrder before the With ws.Sort block to ensure the string is correctly populated in the Immediate Window.

If you receive a "Runtime Error 1004," check your range definitions. This error usually occurs because the SetRange area does not encompass the Key range, or the worksheet name provided in the Set ws line is misspelled or does not exist in the active workbook.

If some rows are sorted correctly but others are not, inspect the cells for non-printing characters. Use the =TRIM() or =CLEAN() functions in a helper column to see if there are invisible characters causing the mismatch. VBA's custom sort is extremely literal; a carriage return inside a cell will break the match with the custom order string.

If the macro runs but nothing happens, ensure that you have included the .Apply method at the end of the With ws.Sort block. The Sort object in VBA builds a set of instructions; none of those instructions are executed until the .Apply command is triggered.

Frequently Asked Questions

Can I use a custom sort for dates?

Yes, though dates are usually sorted numerically. A custom sort is useful for dates if you want to sort by a specific fiscal year sequence or a non-standard calendar that doesn't follow chronological order.

Does the custom order string have a character limit?

Yes, there is a limit to the length of the custom order string. If you have hundreds of items to sort, it is better to use a helper column with a VLOOKUP to assign a numerical rank to each item and then sort by that number.

Can I sort by multiple custom lists at once?

Yes. You can add multiple .SortFields.Add lines within the same With ws.Sort block. Each field can have its own CustomOrder string, allowing for primary, secondary, and tertiary custom sorts.

Will this work on Excel for Mac?

Yes, the Sort object and CustomOrder property are supported in VBA for Mac, although the Visual Basic Editor interface may look slightly different and some keyboard shortcuts may vary.

Do I need to save the file in a special format?

Yes, because the file contains VBA macros, you must save the workbook as an Excel Macro-Enabled Workbook (.xlsm) or a Binary Workbook (.xlsb). Saving as a standard .xlsx will remove all your code.