# Sort text and numbers with formula

To dynamically sort data with both numbers and text in alphabetical order you can use a formula to generate a numeric rank in a helper column, then use INDEX and MATCH to display values based on rank. In the example shown the formula in C5 is :

where "data" is the named range B5:B13.

This formula first generates a rank value using an expression based on COUNTIF:

=COUNTIF(data,"<="&B5)

which is explained in more detail here. If the data contains all text values, or all numeric values, the rank will be correct. However, if the data includes both text and numbers, we need to "shift" the rank of all text values to account for the numeric values. This is done with the second part of the formula here:

Here, we use the COUNT function to get a count of numeric values in the data, then multiply the result by the logical result of ISTEXT, which tests if the value is text and returns either TRUE or FALSE. This effectively cancels out the COUNT result when we are working with a number in the current row.

### Handling duplicates

If data contains duplicates, the formula can be altered as shown below to assign a sequential rank to values that appear more than once:

This version adjusts the logic of the initial COUNTIF function, and adds another COUNTIF with an expanding reference to increment duplicates.

### Display sorted values

To retrieve and display values sorted values in alphabetical order using the calculated rank value, E5 contains the following INDEX and MATCH formula:

where "data" is the named range B5:B13, and "rank" is the named range C5:C13.

For more information about how this formula works, see the example here.

### Dealing with blanks

Empty cells will generate a rank of zero. Assuming you want to ignore empty cells, this works fine because the INDEX and MATCH formula above begins at 1. However, you will see #N/A errors at the end of sorted values, one for each empty cell. An easy way to handle this is to wrap the INDEX and MATCH formula in IFERROR like this:

## Excel Formula Training

Formulas are the key to getting things done in Excel. In this accelerated training, you'll learn how to use formulas to manipulate text, work with dates and times, lookup values with VLOOKUP and INDEX & MATCH, count and sum with criteria, dynamically rank values, and create dynamic ranges. You'll also learn how to troubleshoot, trace errors, and fix problems. Instant access. See details here.