How to Filter By Column Sort By Row in Excel
Learn multiple Excel methods to filter by column and then sort by row with step-by-step examples, real-world scenarios, and practical tips.
How to Filter By Column Sort By Row in Excel
Why This Task Matters in Excel
In many reporting and analysis projects you need to reduce a large data block to only the columns that matter, and then present those selected columns in a meaningful order. Think of a regional sales cube in which each column represents a month, or a financial model that spreads years across columns. Very often you have to:
- keep only the columns that match a dynamic rule (for instance, “include only fiscal years 2019-2021” or “keep departments flagged as Active”),
- reorder the surviving columns based on a key figure that sits in one specific row (for example, “sort the remaining months by total revenue found in row 15”).
If you do those two steps manually—first hiding unwanted columns and then dragging columns into place—you risk errors, you burn time every reporting cycle, and you lose the refresh-ability that makes Excel so powerful. Automating “filter by column, sort by row” eliminates that waste.
Finance teams employ the technique to build rolling quarter dashboards that always show the last three quarters sorted by profitability. Marketing teams use it to surface channels with engagements above a threshold and then display them left-to-right in order of cost per click. Operations analysts apply it to inventory grids to keep only items in stock and arrange them by current quantity.
Because Excel’s modern dynamic array engine can spill entire data blocks automatically, a single formula can now handle both tasks at once. The key players are FILTER, SORT, and SORTBY—often wrapped in LET for clarity. Older versions without these functions can still achieve the goal with INDEX-based constructions, but the dynamic approach is cleaner, faster, and easier to maintain. If you cannot quickly filter columns and then sort them by a row, you will spend hours on repetitive maintenance, risk shipping outdated reports, and miss critical insights such as suddenly top-selling products hidden in the far right of a worksheet. Mastering this workflow also deepens your understanding of array manipulation, which feeds directly into skills like dashboard-level automation, spill-based chart ranges, and flexible ad-hoc modeling.
Best Excel Approach
The most efficient modern solution is a three-function stack:
- FILTER to remove columns that do not meet your header rule.
- SORT or SORTBY to reorder columns based on a chosen row.
- LET (optional) to store intermediate results and keep the formula readable.
Why is this best?
- FILTER and SORT* are native dynamic array functions, so the result automatically resizes when source data changes.
- The by_col argument in SORT—or the capability to supply an entire row as the sort array in SORTBY—allows horizontal sorting, something classic sorting tools cannot do without VBA.
- Everything remains one refreshable formula, ideal for dashboards and shared workbooks.
Prerequisites: Excel 365 or Excel 2021 for FILTER/SORT. Classic Excel can use INDEX-AGGREGATE alternatives (covered later). Data must be a true rectangle (no merged cells in the block you are filtering). Row numbers you reference for sorting must contain comparable values (all numbers or all text).
Syntax overview with the most flexible combo:
=LET(
data, B4:M20, /* full source block */
headers, B3:M3, /* header row used to filter */
keep, (headers>=2019)*(headers<=2021), /* logical test per column */
base, FILTER(data, keep, ""), /* filtered columns only */
keyRow, 17-3+1, /* convert actual row 17 to row index inside data */
sorted, SORT(base, keyRow, -1, TRUE), /* sort columns by that row, descending */
sorted )
Parameter notes:
- data – entire table minus header row if you want to exclude it from sort.
- keep – logical array the same size as headers indicating which columns survive.
- keyRow – which row inside the data block drives the sort (1 = first row in data).
- TRUE in SORT forces horizontal sorting “by column”.
Alternative using SORTBY (nicer when you want to sort on multiple rows or on calculated row arrays):
=LET(
data, B4:M20,
headers, B3:M3,
keep, ISNUMBER(MATCH(headers, {"North","South","West"}, 0)),
base, FILTER(data, keep, ""),
key, INDEX(base, 14, ), /* pick row 14 of the filtered set */
SORTBY(base, key, 1) /* ascending based on that row */ )
SORTBY automatically detects orientation, so you do not need by_col TRUE.
Parameters and Inputs
Data block (array): a contiguous rectangle, for instance [B4:M20]. Mixed data types are fine, but the row you use as a key should contain elements that Excel can compare consistently (numbers with numbers, text with text).
Header row (array): the row used to decide which columns to keep. This can be the first row of the data block or a separate reference like [B3:M3].
Logical include test: any expression that evaluates to TRUE or FALSE for each header position. Typical patterns are equality with a value, range tests, or membership tests with MATCH/ISNUMBER.
Sort row index or array: either a row number inside the filtered dataset or an explicit array such as INDEX(base, 12, ).
Sort order: 1 for ascending, ‑1 for descending.
by_col flag (SORT only): TRUE to sort horizontally. Omit when using SORTBY.
Fallback value in FILTER: text or number returned when no columns pass the filter. Keep it empty string \"\" to spill nothing but avoid an error.
Edge cases:
- All columns excluded ⇒ FILTER returns the fallback; subsequent SORT must not process an empty array. Wrap the entire stack in IFERROR if the data may shrink to zero.
- Duplicate header labels ⇒ The logic still works; FILTER evaluates keep per position, not per unique label.
- Key row contains errors (for example divide-by-zero) ⇒ Sorting sees error values as larger than any number. Clean or wrap the key calculation in IFERROR.
Step-by-Step Examples
Example 1: Basic Scenario – Filter Years 2019-2021, Sort by Total Row
Suppose you maintain a small revenue table where each column is a year and each row is a product category.
Sample layout
A3 B3 C3 D3 E3
2018 2019 2020 2021
A4 Electronics
A5 Clothing
A6 Beauty
A7 Total
Numeric data fills [B4:E6]. Row 7 contains SUMs. Management wants to see only the last three years and have those columns appear left-to-right by the total revenue (largest first).
- Identify ranges
- data = [B4:E6]
- headers = [B3:E3]
- Build keep logic:
=(headers>=2019)*(headers<=2021)
This yields [FALSE, TRUE, TRUE, TRUE].
- Write the LET formula:
=LET(
data, B4:E6,
headers, B3:E3,
keep, (headers>=2019)*(headers<=2021),
base, FILTER(data, keep, ""),
key, INDEX(base, 4, ), /* row 4 inside base is Total */
SORTBY(base, key, -1) )
- Press Enter. Excel spills three columns containing 2019-2021, ordered by the totals Row 7. If Total for 2020 is highest, that column appears first.
Why it works: FILTER uses the keep array to pass only columns 2019-2021. INDEX(base, 4, ) extracts the fourth row (total) of the filtered block as a 1×3 array. SORTBY reorders the columns based on that key. Everything updates automatically when new data arrives.
Troubleshooting tips
- If nothing spills, check that headers are truly numbers, not text “2019”.
- If the wrong row seems to drive sorting, remember that INDEX uses the position inside base, not the original sheet. Count from the top of your filtered output.
Example 2: Real-World Application – Active Departments Dashboard
A company tracks expense accounts by department across 12 months. HR flags departments as Active or Inactive in a small table. Finance needs a one-glance dashboard that:
- Keeps only departments flagged Active (filter by column).
- Sorts those remaining departments by year-to-date operating cost located in row 28.
- Refreshes the layout each time the HR flag or cost numbers change.
Data structure
- Row 3: department labels (Sales, R&D, Admin, etc.).
- Row 4: Active flag (TRUE/FALSE or 1/0).
- Rows 5-27: monthly expenses.
- Row 28: total expenses (SUM of rows 5-27).
- Range: [C3:N28] (first two rows are labels and flags).
Step-by-step
- Add two named ranges for clarity:
- deptHeaders = [C3:N3]
- deptActive = [C4:N4]
- Write the formula in a separate dashboard sheet:
=LET(
data, C5:N28,
active, deptActive,
keep, active=TRUE,
base, FILTER(data, keep, ""),
ytd, INDEX(base, 24, ), /* Row 24 inside base = YTD total */
SORTBY(base, ytd, 1) ) /* ascending, lowest spender first */
- Format the spilled range as a table or reference it in PivotCharts.
Business value
- HR changes the flag in row 4 ⇒ the dashboard instantly hides or reveals the department columns.
- Monthly close updates cost rows ⇒ YTD totals change ⇒ columns resort themselves.
- No one touches the formula again; the CFO can always view Active departments left-to-right from leanest to most expensive.
Performance considerations
With 10 departments × 12 months × multiple years, you spill only relevant columns, which reduces downstream formula load and chart refresh time. Using LET also ensures Excel calculates each variable once, not repeatedly.
Example 3: Advanced Technique – Dynamic Column Grouping with CHOOSECOLS and Multiple Sort Keys
Scenario: A multinational retailer wants to display quarterly sales for the regions that beat plan and order those regions first by customer satisfaction score (row 35), then by revenue growth percentage (row 42). They also want an optional parameter in cell P2 that controls the year being viewed.
Setup
- Data in [B6:AL80], where columns represent Region-Year combinations (e.g., “North 2022 Q1”).
- Row 4 contains the Region name, row 5 the Year, row 6 the Quarter.
- Row 35 holds weighted customer satisfaction, row 42 revenue growth.
- Cell P2 contains the Year to display.
Goals
- Filter columns where Year equals P2.
- Among those, further reduce to Regions flagged “Beat” plan (a separate Boolean row 7).
- Sort by Row 35 (descending) then row 42 (descending).
Power formula:
=LET(
data, B8:AL80,
region, B4:AL4,
yr, B5:AL5,
beat, B7:AL7,
yearSel, P2,
keep, (yr=yearSel)*(beat=TRUE),
base, FILTER(data, keep, ""),
csat, INDEX(base, 28, ),
growth, INDEX(base, 35, ),
SORTBY(base, csat, -1, growth, -1) )
Explained:
- keep multiplies two logical conditions so both must be TRUE.
- base is the sales matrix now limited to Region columns that both belong to the selected year and beat plan.
- SORTBY accepts multiple sort arrays: first customer satisfaction, then growth.
- The result automatically trims and sorts columns horizontally every time P2 changes.
Optimizations & professional tips
- Replace FILTER with TAKE+CHOOSECOLS (Excel beta) when you already know column positions—this can be faster on 100,000-cell ranges.
- Wrap in IFERROR(\"No match\") to display a user-friendly message if no region qualifies.
- Drive the keep logic with a Spill range named criteriaList to enable interactive slicer-style selection.
Tips and Best Practices
- Use LET to store subarrays. This makes long formulas readable and Excel calculates each piece once, improving speed on big models.
- Always test the include array separately (select it in the formula bar and press F9) to verify TRUE/FALSE positions before wrapping with FILTER.
- For stable dashboards, freeze the sort row with an independent calculation (e.g., total stored in a helper row) so users editing other rows do not inadvertently reshuffle columns.
- Name ranges for header rows and frequently used parameters; this avoids off-by-one mistakes when sheets expand.
- When sorting text that mixes upper and lower case, normalize with LOWER or UPPER inside the key array to ensure consistent ordering.
- If you cascade the result into charts, convert the spill to a dynamic named range (e.g., =FILTERSort) so the chart always captures the latest shape without manual adjustment.
Common Mistakes to Avoid
- Mixing text and numbers in the sort row – Excel treats text as larger than numbers, so columns may jump unpredictably. Keep the key row homogeneous or convert everything with VALUE or TEXT.
- Forgetting by_col TRUE in SORT – Leaving the fourth argument blank causes vertical sorting, which rearranges rows rather than columns. Use SORTBY if you prefer not to remember the argument order.
- Creating a keep array of mismatched size – FILTER throws a #VALUE! spill if the include array height differs from the data’s width when filtering columns. Double-check that your keep array is 1-by-N where N equals the number of columns.
- Referencing absolute row numbers after filtering – Once data is filtered, row positions shift. Use INDEX(base, rowIndex, ) where rowIndex is relative to the base array.
- Hard-coding year thresholds – Instead of (headers ≥ 2019), link thresholds to driver cells so end-users can change them without editing the formula.
Alternative Methods
Below is a comparison of other ways to achieve “filter columns, sort by row”:
| Method | Key Functions | Pros | Cons | Best When |
|---|---|---|---|---|
| Dynamic arrays (FILTER + SORTBY) | FILTER, SORT, SORTBY | Single formula, auto-spill, easiest to read | Requires Excel 365/2021 | Modern Excel, frequent refresh |
| INDEX + AGGREGATE loop | INDEX, SMALL/LARGE, COLUMNS | Works in Excel 2010-2019 | Long formulas, volatile, tough to maintain | Legacy versions without dynamic arrays |
| Power Query | GUI filter by column, then transpose + sort | No formulas, repeatable query refresh | Separates data from worksheet grid, needs refresh click | ETL workflows, very large datasets |
| VBA macro | Loops through columns, hides and reorders | Unlimited logic flexibility | Requires macro-enabled file, security prompts | Custom UI buttons, heavy automation |
Performance: dynamic arrays recalculate instantly on blocks up to 20,000 cells. Power Query excels on millions of rows but does not recalc in real time, making it better for periodic loads. INDEX loops are slower and should be phased out when upgrading.
Migration strategy: After upgrading to 365, wrap legacy INDEX formulas inside comments, then recreate with FILTER+SORTBY. Test results side-by-side before removing the old logic.
FAQ
When should I use this approach?
Use it whenever you need a live subset of columns plus a dynamic left-to-right order—rolling forecasts, region scorecards, departmental variance reports, or any dashboard where visibility and order shift with the data.
Can this work across multiple sheets?
Yes. Point the data and header references at a different sheet, e.g., Sheet1!B4:M20. The spill still appears where the formula resides. If the header row lives elsewhere, reference it fully: Sheet1!B3:M3.
What are the limitations?
FILTER returns a maximum of 1,048,576 rows or 16,384 columns (worksheet limits). The include test must be the same orientation as the dimension you filter. In Excel for Web, very wide spills may truncate if memory is low.
How do I handle errors?
Wrap the entire LET stack in IFERROR to capture #CALC! from empty filters or #VALUE! from mismatched sizes:
=IFERROR( yourFormula , "No columns meet criteria" )
Alternatively, provide the third argument of FILTER to display a custom message when nothing matches.
Does this work in older Excel versions?
Not natively. Excel 2019 and earlier lack FILTER and SORTBY. Use the INDEX-based alternative or migrate to 365. Power Query remains an option even in Excel 2010.
What about performance with large datasets?
Dynamic arrays are efficient because they calculate at the range level rather than per cell. Still, keep source blocks reasonable (under 100,000 cells) for instant recalc. Turn off automatic calculation for monster workbooks or offload heavy prep to Power Query.
Conclusion
Knowing how to filter by column and then sort by row unlocks a powerful level of flexibility in Excel. You can present the exact slice of data your audience needs, in the precise order that tells the best story, all with a single self-maintaining formula. The same skill scales from tiny tables to enterprise-level dashboards and dovetails with array thinking, named ranges, and spill charts. Practice the examples above, experiment with LET for clarity, and soon you’ll be building interactive, refresh-free views that impress managers and save hours every month.
Related Articles
How to Show the 10 Most Common Text Values in Excel
Learn multiple Excel methods to list the 10 most frequent text values—complete with step-by-step examples, business use cases, and expert tips.
How to Abbreviate Names Or Words in Excel
Learn multiple Excel methods to abbreviate names or words with step-by-step examples and practical applications.
How to Abbreviate State Names in Excel
Learn multiple Excel methods to abbreviate state names with step-by-step examples, professional tips, and real-world applications.