Skip to main content
ExcelSort by Custom Order (MATCH)Lookup & ReferenceData SortingDynamic Arrays

The Problem

Have you ever looked at a beautifully organized spreadsheet, only to realize the "order" isn't quite right? Standard alphabetical or numerical sorting often falls short when your data has a specific, logical sequence that Excel doesn't inherently understand. Perhaps you need to list product categories like "Produce," "Dairy," "Meat," then "Bakery," instead of the default alphabetical "Bakery," "Dairy," "Meat," "Produce." This seemingly simple task can become a major headache, especially with large datasets, leading to manual reordering errors and wasted time.

What is SORT? The SORT function is an Excel dynamic array function that sorts a range or array. It is commonly used to reorder data based on specified columns and sort orders (ascending/descending). While powerful, SORT alone doesn't directly support custom, non-standard ordering. This is where MATCH comes in, acting as the clever ingredient to give SORT the precise instructions it needs.

Business Context & Real-World Use Case

Imagine you're a project manager overseeing a complex software development lifecycle. Your project tasks often follow specific phases: "Discovery," "Design," "Development," "Testing," and "Deployment." When you export a list of tasks from your project management system, it often sorts them alphabetically, or by due date, but rarely by the actual project phase sequence. Manually dragging and dropping rows to get the correct phase order in a Gantt chart or status report is not only tedious but also highly prone to errors. A misplaced task could lead to miscommunication, delayed deadlines, or incorrect resource allocation.

In my years as a data analyst, I've seen teams waste hours manually reordering product categories for sales reports, or restructuring operational steps for process documentation. Automating this custom sorting ensures consistency, accuracy, and frees up valuable time for more critical analysis. By leveraging the SORT function with the power of MATCH, you can instantly transform chaotic data into a logically ordered, presentation-ready format, giving stakeholders clear insights into progress and priorities. This skill is invaluable for anyone creating structured reports, managing inventories, or tracking project progress.

The Ingredients: Understanding Sort by Custom Order (MATCH)'s Setup

The SORT function is incredibly versatile, especially when paired with other dynamic array functions. To achieve a custom sort order, we'll combine SORT with MATCH and HSTACK (Horizontal Stack) to create a temporary "helper column" within our formula. This helper column will assign a numerical rank based on your desired custom order, which SORT can then easily understand.

Here’s the basic syntax for the SORT function:

=SORT(array, [sort_index], [sort_order], [by_col])

Let's break down each parameter for our custom sorting recipe:

Variable Description
array This is the range or array you want to sort. For custom sorting, we'll construct a temporary array here using HSTACK. This temporary array will include a numerical "sort key" (generated by MATCH) as its first column, alongside your original data.
sort_index (Optional) A number indicating the row or column index to sort by. For our custom sort, this will always be 1, as we will create our MATCH-generated sort key as the first column of our temporary array.
sort_order (Optional) A number indicating the sort order: 1 for ascending (smallest to largest, or A to Z), -1 for descending (largest to smallest, or Z to A). Since MATCH returns numbers (1, 2, 3...) corresponding to the custom order, we will almost always use 1 here to sort those numbers in ascending order, thereby achieving our custom sequence.
by_col (Optional) A logical value: TRUE to sort by column, FALSE to sort by row. The default is FALSE (sort by row). For most custom sorting scenarios involving lists, you'll either omit this or use FALSE as we're usually sorting rows of data.

The MATCH function's role is critical. MATCH(lookup_value, lookup_array, [match_type]) will return the relative position of lookup_value within lookup_array. By defining lookup_array as our custom sort order, MATCH effectively translates each item from our original data into a numeric rank that SORT can then use.

The Recipe: Step-by-Step Instructions

Let's walk through a practical example. Imagine you have a list of product categories and their sales figures. You want to sort these categories in a specific, non-alphabetical order: "Produce", "Dairy", "Meat", "Bakery", "Frozen".

Here's our sample data in a sheet starting from cell A1:

Category Sales (USD)
Bakery 1200
Meat 2500
Produce 3000
Dairy 1800
Frozen 900
Bakery 1500
Dairy 2100
Meat 2800
Produce 3500

Our goal is to sort this data based on the custom order: {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}.

Here's how to build the custom sorting formula step-by-step:

  1. Select Your Cell: Click on an empty cell where you want your sorted data to appear, for example, cell D2. This is where the dynamic array output will spill.

  2. Define Your Custom Order Array: First, determine your custom sort order. For our example, this is {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}. Note the use of semicolons to create a vertical array when hardcoding within a formula. If your custom order list is in a range (e.g., C2:C6), you would simply reference that range.

  3. Generate Custom Sort Keys with MATCH: We'll use MATCH to assign a numeric rank to each category in your original data (A2:A10) based on our custom order.

    • MATCH(A2:A10, {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}, 0)
    • This part of the formula takes each category from A2:A10 and finds its position in our custom order list. "Produce" would become 1, "Dairy" would be 2, "Meat" 3, and so on.
  4. Combine Custom Sort Keys with Original Data using HSTACK: Now, we'll create a temporary array that combines these MATCH-generated sort keys with your original data (A2:B10). HSTACK is perfect for this, stacking arrays horizontally.

    • HSTACK(MATCH(A2:A10, {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}, 0), A2:B10)
    • This creates a three-column temporary array. The first column will contain the numeric ranks (from MATCH), and the next two columns will be your original "Category" and "Sales (USD)" data.
  5. Sort the Combined Array with SORT: Finally, we wrap the HSTACK result in the SORT function. We tell SORT to sort this combined array by its first column (which contains our custom sort keys) in ascending order.

    • =SORT(HSTACK(MATCH(A2:A10, {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}, 0), A2:B10), 1, 1)
    • Here, the array argument is our HSTACK result. sort_index is 1 (to sort by the MATCH column), and sort_order is 1 (ascending).

The final working formula you would enter in cell D2 is:

=SORT(HSTACK(MATCH(A2:A10,{"Produce";"Dairy";"Meat";"Bakery";"Frozen"},0), A2:B10), 1, 1)

This formula will output a new, dynamically sorted table. The first column of the output will contain the numerical sort keys (1 for Produce, 2 for Dairy, etc.), followed by your Category and Sales data, all perfectly ordered according to your custom sequence.

Here's what the result in your sheet (starting from D2) would look like:

Custom Key Category Sales (USD)
1 Produce 3000
1 Produce 3500
2 Dairy 1800
2 Dairy 2100
3 Meat 2500
3 Meat 2800
4 Bakery 1200
4 Bakery 1500
5 Frozen 900

As you can see, the data is now sorted precisely in your custom order, with "Produce" items appearing first, then "Dairy", and so on. The "Custom Key" column is a temporary artifact that helps SORT achieve this.

Pro Tips: Level Up Your Skills

Mastering the SORT function with custom ordering using MATCH significantly enhances your data manipulation capabilities. Here are a few expert tips to elevate your game:

  1. Refine Your Output with DROP: Notice the MATCH key column in the output? While essential for sorting, it might not be needed in your final report. You can easily remove this column by wrapping your entire formula in the DROP function. For our example, =DROP(SORT(HSTACK(MATCH(A2:A10,{"Produce";"Dairy";"Meat";"Bakery";"Frozen"},0), A2:B10), 1, 1),,1) would remove the first column, leaving only your sorted Category and Sales data.
  2. Store Custom Lists in a Range: Hardcoding your custom order list directly into the formula (like {"Produce";"Dairy";"Meat";"Bakery";"Frozen"}) makes it difficult to update. Instead, store your custom order in a dedicated range on your spreadsheet (e.g., C2:C6). Then, simply reference this range in your MATCH function: MATCH(A2:A10, C2:C6, 0). This makes your formula much more flexible and easier to maintain.
  3. Use Caution When Scaling Arrays Over Massive Rows: Dynamic array formulas, while powerful, perform calculations across entire ranges. When dealing with tens of thousands or hundreds of thousands of rows, complex formulas involving SORT, HSTACK, and MATCH can impact performance. Experienced Excel users monitor calculation times and optimize by structuring data efficiently or leveraging Power Query for very large datasets if responsiveness becomes an issue.
  4. Handle Missing Values Gracefully: What if some items in your data aren't present in your custom order list? The MATCH function will return an #N/A error for those items. You can use IFNA to assign a default sort position (e.g., put all unmatched items at the end by assigning them a very high number) or use XLOOKUP which has a built-in if_not_found argument.

Troubleshooting: Common Errors & Fixes

Even seasoned chefs occasionally burn a dish. With dynamic array formulas, understanding common errors is key to quick problem-solving. Here are some issues you might encounter when sorting with SORT and MATCH.

1. #VALUE! Error

  • What it looks like: The entire formula result spills #VALUE!, or in some cases, HSTACK might return #VALUE!.
  • Why it happens: The #VALUE! error often indicates a mismatch in argument types or dimensions. A common cause is an incorrect orientation of your custom order array within MATCH. If MATCH's lookup_value is a vertical range (e.g., A2:A10), its lookup_array (your custom order list) should also be vertical ({"Produce";"Dairy";"Meat"} using semicolons, or a vertical range reference like C2:C6). Using commas {"Produce","Dairy","Meat"} would create a horizontal array, leading to a dimension mismatch when MATCH tries to compare with a vertical range. Another cause can be HSTACK arguments not having compatible row counts.
  • How to fix it:
    1. Check MATCH Array Orientation: If you're hardcoding your custom order list, ensure you're using semicolons (;) for a vertical array: {"Item1";"Item2";"Item3"}. If your custom order is in a worksheet range, confirm it's a single column (vertical).
    2. Verify HSTACK Dimensions: Ensure the range for MATCH (e.g., A2:A10) and your data range (e.g., A2:B10) have the same number of rows. If they don't, HSTACK will struggle to combine them correctly, potentially resulting in #VALUE!.

2. #N/A Error (within the output)

  • What it looks like: The sorted output contains #N/A errors, particularly in the first column (the MATCH key) and the corresponding data rows.
  • Why it happens: This error originates from the MATCH function. It signifies that a value in your data column (e.g., a category in A2:A10) could not be found within your specified custom order list. When MATCH can't find a lookup_value in its lookup_array, it returns #N/A. This #N/A then propagates through the HSTACK and SORT functions.
  • How to fix it:
    1. Review Data and Custom List: Carefully compare the unique values in the column you're sorting by (e.g., A2:A10) with the items in your custom order list. Look for typos, extra spaces, or missing entries in either list.
    2. Expand Custom Order List: If valid data points are missing from your custom order, add them to your custom list (or the range where it's stored).
    3. Implement Error Handling (Advanced): For more robust solutions, consider wrapping the MATCH function in an IFNA or XLOOKUP function to handle unmatched items gracefully. For example, IFNA(MATCH(A2:A10, custom_order, 0), 9999) would assign a very high sort key (like 9999) to unmatched items, effectively pushing them to the end of the sort order.

3. Incorrect Sorting Order (Logic Error)

  • What it looks like: The formula executes without error messages, but the data is not sorted in the desired custom order. It might still appear alphabetically, or in some other unintended sequence.
  • Why it happens: This is typically a logical error, meaning the formula is syntactically correct but its instructions don't align with your intent. Common culprits include:
    • Incorrect Custom Order List: The sequence of items in your {"Produce";"Dairy";"Meat";...} array might not be exactly what you intended.
    • Wrong sort_order: If you used -1 for sort_order in the SORT function (descending), it would sort the MATCH keys (1, 2, 3...) in reverse (3, 2, 1...), leading to an inverted custom order.
    • sort_index Mismatch: While less common with our HSTACK approach (where sort_index is always 1), if you were attempting a more complex sort and referenced the wrong column number for sort_index, it would lead to incorrect results.
  • How to fix it:
    1. Verify Custom Order Sequence: Double-check your custom order list for accuracy. Ensure the items are listed in the exact sequence you want them to appear in the final output.
    2. Confirm sort_order is 1: For MATCH-generated sort keys, you almost always want sort_order to be 1 (ascending) so that items with key 1 come before 2, and so on. Ensure your SORT function has 1 as its third argument.
    3. Inspect HSTACK Output: Temporarily remove the SORT function and evaluate just the HSTACK portion of the formula. This will show you the temporary array, including the MATCH keys. Verify that the MATCH keys are being generated correctly (e.g., "Produce" items all have a '1' in the first column, "Dairy" items have a '2', etc.). This can quickly highlight issues in your MATCH setup.

Quick Reference

Feature Description
Syntax =SORT(HSTACK(MATCH(lookup_array, custom_order_list, 0), original_data_array), 1, 1)
Use Case Reordering data based on a specific, non-alphabetical or non-numeric sequence (e.g., project phases, product categories, educational grades).
Key Benefits Dynamic, avoids helper columns on the sheet, enhances report readability, reduces manual errors.
Best Practice Store your custom order list in a dedicated cell range for easy updates. For very large datasets, consider Power Query for performance.

Related Functions

👨‍💻

Written by The Head Chef

Former 10-year Financial Analyst who survived countless month-end closes. I build these recipes to save you from weekend-ruining spreadsheet errors.

Read the full story →

You might also find these useful 💡