Sub topic 10
Sorting and filtering
This chapter assumes you can already create a table, rename it, and enter formulas that use structured references. Here you work with the header buttons that every table gets. You will sort and filter data without breaking formulas, and you will see why a filtered table and a total row interact the way they do.
What the header buttons do
When you create a table, each header cell gets a drop-down arrow. Both sorting and filtering live in that menu. You can add the same arrows to a plain range with Data > Filter, but a table handles them better in these ways:
- The filter range is the table itself. You never reselect the range, and new rows join it automatically.
- A worksheet can hold only one AutoFilter on a plain range. Each table carries its own filter, so several tables can share a sheet and be filtered independently.
- The arrows replace the column letters when you scroll down, so you can still use them while the headers are out of view.
- The sort and filter settings are stored with the table and survive saving and reopening.
Rows hidden by a filter are not deleted. Excel hides the row, and the row numbers on the left turn blue to show that a filter is active.
Sorting a table
Open a header drop-down and choose Sort A to Z, Sort Z to A, or Sort Smallest to Largest. Excel sorts only the table's rows. Cells beside or below the table are left alone, so there is no risk of splitting related data, which is a common error when sorting plain ranges.
Multi-level sorts
One column rarely gives a useful order. Use Data > Sort (or Home > Sort & Filter > Custom Sort) to add levels:
- Click any cell inside the table.
- Open Data > Sort.
- Choose the first column under Sort by, then add levels with Add Level.
- Choose the sort key for each level (Cell Values, Cell Color, Font Color, or Cell Icon) and the order.
Excel applies the levels from top to bottom. Rows that tie on level one are ordered by level two, and so on. A sort by Region, then Amount from largest to smallest, groups each region together with its biggest sales first.
For text such as "High", "Medium" and "Low", alphabetical order puts them in the wrong sequence. Choose Custom List under Order to define the sequence yourself.
Sorts are not live
A sort is applied once. If you sort by Amount and then add a row, the new row is not placed in order. Reapply the sort with Data > Reapply, or open the Sort dialog and click OK again. This surprises many users because Excel does keep the sort criteria stored with the table. It only reapplies them when you ask.
Filtering a table
The filter menu changes with the column's data type:
| Column contains | Filter submenu | Example criteria |
|---|---|---|
| Text | Text Filters | Begins With, Contains, Does Not Contain |
| Numbers | Number Filters | Greater Than, Between, Top 10, Above Average |
| Dates | Date Filters | This Month, Next Quarter, Between, a year or month from the tree |
| Colored cells | Filter by Color | A specific fill or font color |
Every menu also has a checklist of the unique values in the column and a search box above it. Typing in the search box narrows the checklist as you type, and you can then tick the matches. If a date column shows Text Filters instead of Date Filters, the dates were entered as text. Fix the data before relying on the filter.
Filtering across several columns
Filters on different columns combine with AND. If you filter Region to West and Amount to greater than 500, you see only West rows above 500. Within one column, ticking several values is OR, so ticking West and East shows rows from either region.
Each header arrow changes to a funnel icon when its column is filtered. Hover over it to see the criteria.
Clearing filters
Use the drop-down command Clear Filter From "Column" to remove one column's filter. Use Data > Clear to remove every filter on the table at once. Clearing does not remove the arrows. To switch the arrows off entirely, use Data > Filter, or clear Filter Button on the Table Design tab.
Filters are not live either
Like sorts, filters are not reapplied when data changes. If you filter to West and then change a row's region to East, that row stays visible until you use Data > Reapply. A row you add at the bottom of a filtered table also remains visible even if it does not match.
How filtering affects formulas
Formulas that read hidden rows do not all behave the same way. This matters because many tables carry a summary somewhere.
SUM,COUNTandAVERAGEinclude every row, hidden or not.SUBTOTALignores rows hidden by a filter.SUBTOTALwith function numbers 101 to 111 also ignores rows you hid by hand. The numbers 1 to 11 ignore only filtered rows.
The total row uses SUBTOTAL for this reason. You can write the same thing yourself in a cell outside the table:
=SUBTOTAL(109,SalesTable[Amount])To count the visible rows, use function number 103, which is COUNTA with hidden rows excluded:
=SUBTOTAL(103,SalesTable[Customer])If you want a plain SUM in a summary cell, it will keep showing the grand total while the table is filtered. Use SUBTOTAL when the summary should follow the filter.
Sorting and calculated columns
A calculated column that uses only [@Column] references sorts safely, because each row refers only to itself:
=[@Quantity]*[@[Unit Price]]Trouble starts when a formula points at another row. A running total such as =SUM(E$2:E2) or a formula that reads the row above can return different results after a sort, because the neighboring rows have changed. Test these formulas after sorting. If a column must depend on row order, add a number column that records the original order, so you can sort back to it.
References to other sheets or to cells outside the table are not shifted by a sort. A formula in another sheet such as =SalesTable[@Amount] is not a normal use, so refer to a specific row by looking it up with INDEX or XLOOKUP, not by position.
Sorting and filtering with VBA
The ListObject object exposes both features. The macro below clears any active filter, sorts by Region and then by Amount from largest to smallest, and filters to West:
Sub SortAndFilterSales()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("SalesTable")
If tbl.AutoFilter.FilterMode Then tbl.AutoFilter.ShowAllData
With tbl.Sort
.SortFields.Clear
.SortFields.Add Key:=tbl.ListColumns("Region").DataBodyRange, _
SortOn:=xlSortOnValues, Order:=xlAscending
.SortFields.Add Key:=tbl.ListColumns("Amount").DataBodyRange, _
SortOn:=xlSortOnValues, Order:=xlDescending
.Header = xlYes
.Apply
End With
tbl.Range.AutoFilter Field:=tbl.ListColumns("Region").Index, Criteria1:="West"
End SubThe Field argument is the column's position within the table, not the worksheet column letter. Using ListColumns(...).Index keeps the macro correct if someone moves the table. The sheet must contain a table named SalesTable with Region and Amount columns.
Common errors
- A filter list is missing recent values. The drop-down shows values as of the last time it was built. Reopen the menu after adding rows, and use Reapply if the filter should now include the new data.
- Blank cells sort to the bottom. Excel always places blanks last, in both ascending and descending order.
- Numbers stored as text sort after real numbers and appear under Text Filters. Convert them with Data > Text to Columns or by multiplying a helper column by 1.
- Merged cells block sorting. Tables do not allow merged cells in their body, so this error appears when you try to sort a plain range that you converted from merged cells. Unmerge before creating the table.
- A sort seems to have no effect. Check that a cell inside the table is selected, and that no second sort level overrides the first.
Exercise
A table named SalesTable has a Region column and an Amount column. You filter Region to West. Cell H1 contains =SUM(SalesTable[Amount]) and cell H2 contains =SUBTOTAL(109,SalesTable[Amount]). Which cell shows the total for West only, and what happens to each cell if you then add a new East row at the bottom of the table while the filter is still active?
Show answer
H2 shows the West total, because SUBTOTAL ignores rows hidden by the filter, while H1 shows the total for all regions. The new East row is added to the table and stays visible, because filters are not reapplied automatically when you add a row. H1 includes the new amount. H2 also includes it, since the row is visible. After you use Data > Reapply, the East row is hidden and H2 drops back to the West total, while H1 is unchanged.
Exercise
You sort a table by Amount from largest to smallest and then type a new row at the bottom. The new row has the highest amount but sits at the bottom. Why, and how do you fix it?
Show answer
Sorts are applied once and are not live, so Excel does not reorder the table when you add data. Reapply the sort with Data > Reapply, or open Data > Sort and click OK.