How to Sum If Cells Contain Both X And Y in Excel

Learn multiple Excel methods to sum if cells contain both x and y with step-by-step examples and practical applications.

excelformulaspreadsheettutorial
12 min read • Last updated: 7/2/2025

How to Sum If Cells Contain Both X And Y in Excel

Why This Task Matters in Excel

Many business datasets contain coded or multi-tagged descriptions in a single column—think product descriptions that list materials, invoice lines that combine project codes, or survey responses that embed multiple keywords. When analysts have to answer a seemingly simple question such as “How much revenue came from products that are both eco-friendly and handmade?” they quickly discover that a normal SUM or even a single-criteria SUMIF is not enough. The challenge is filtering on two different pieces of text within the same cell before aggregating the values that sit alongside those cells.

In marketing analytics, for example, campaign names often contain several identifiers: region, channel, and promotion type. Finance teams tag transactions with cost-center and project codes in the same field to keep import files compact. Inventory managers append multiple attributes—such as “organic, fair-trade” or “men, winter”—inside the SKU description. In all these cases, decision makers need to slice numbers where a data row satisfies two text markers simultaneously.

Excel is particularly strong for this task because it offers several built-in functions that evaluate multiple conditions in one step. Unlike database systems that may require subqueries or complicated joins, Excel lets you write a single cell formula that instantly updates when new rows arrive. When you master the ability to “sum if cells contain both X and Y,” you unlock faster ad-hoc reporting, cleaner dashboards, and smoother collaboration with colleagues who may not be comfortable with SQL or BI tools.

Failing to understand this skill can lead to manual filtering, copying, and pasting totals—error-prone steps that waste time and threaten data integrity. Worse, decisions made on partial or mis-filtered data can misallocate budgets or misstate performance. By learning the methods below, you will not only avoid these pitfalls but also connect this technique to larger workflows such as dynamic dashboards, pivot tables, and Power Query transformations.

Best Excel Approach

The SUMIFS function is the most direct and flexible way to aggregate numbers based on a single column that must contain both substring X and substring Y. Introduced in Excel 2007, SUMIFS supports multiple criteria, and each criterion can use wildcards to look for a substring anywhere within the cell. Its syntax keeps the logic readable, and the function is fully compatible with all modern Excel versions, Office scripts, and even many third-party spreadsheet tools.

The core idea is to feed the same criteria_range twice, once for each substring, so the two tests are applied to the very same cell. The wildcards asterisk (*) and question mark (?) let us treat “contains” rather than “equals” as the match logic. We place asterisks before and after each substring to signal “X can appear anywhere in the text.”

=SUMIFS(sum_range, criteria_range, "*X*", criteria_range, "*Y*")

When to use this approach:

  • Any time you have a single text column that may include both tags
  • Situations where order does not matter—“blue-large” or “large-blue” both match
  • Workbooks that must stay backward compatible with Excel 2007 or newer

Prerequisites:

  • Clean text, without hidden line breaks that might break wildcard matches
  • Consistent capitalization if you do not care about case sensitivity (SUMIFS is not case sensitive)

If you need case sensitivity or dynamic criteria counts, consider the SUMPRODUCT or FILTER methods covered later, but SUMIFS remains the first choice for clarity, speed, and portability.

Parameters and Inputs

Before diving into examples, understand what each argument in the recommended SUMIFS pattern does:

  • sum_range – The numeric cells to add up, e.g., [C2:C1000]. These could be sales amounts, hours, costs, etc.
  • criteria_range – The text cells you want to inspect for X and Y, e.g., [B2:B1000]. In the typical one-column setup, you reference the same range twice within the formula.
  • "*X*" – A text string wrapped in double quotes with asterisks on both sides (wildcards). Replace X with your first keyword.
  • "*Y*" – Same structure, but Y is your second keyword.

Optional considerations:

  • If your data might contain trailing spaces, wrap criteria_range in TRIM within a helper column or use data cleansing tools.
  • For dynamic criteria (stored in cells), concatenate the wildcards: "*"&E1&"*" so the user can simply type the keyword in E1.
  • If sum_range and criteria_range are different sizes, SUMIFS returns zero. Always validate matching dimensions.
  • For numbers stored as text, convert them with VALUE or multiply by 1 in a helper column so that SUMIFS can add them correctly.
  • For inputs containing commas, non-breaking spaces, or language-specific characters, ensure your system’s regional settings align or pre-clean with SUBSTITUTE.

Edge case tip: If X or Y might itself contain an asterisk or question mark (rare but possible with product codes), escape it by using a tilde (~) before the special character in your criteria.

Step-by-Step Examples

Example 1: Basic Scenario

Imagine a small craft-shop ledger. Column B contains item descriptions, and Column C contains sales revenue.

B (Description)C (Revenue)
eco bamboo tray55
handmade cotton bag42
handmade bamboo coaster37
eco glass bottle21
handmade eco candle30

Goal: Sum revenue where the description contains BOTH “handmade” and “bamboo.”

  1. Select an empty cell, e.g., E2, and enter:
=SUMIFS(C2:C6, B2:B6, "*handmade*", B2:B6, "*bamboo*")
  1. Press Enter. Result: 37 (only the third row meets both conditions).

Why it works:

  • Excel scans B2:B6, keeps rows that include the word “handmade,” then further narrows to rows that also contain “bamboo.”
  • Because the criteria are additive (AND logic), only cells passing all tests contribute their Column C value.

Variations:

  • Swap criteria order—it does not matter.
  • Make the keywords dynamic by referencing cells D1 and D2 with "*"&D1&"*" syntax.

Troubleshooting:

  • If the formula returns zero but you expect a value, inspect hidden spaces by selecting the cell and checking the formula bar. TRIM or CLEAN can fix stray characters.
  • If capitalization seems inconsistent, remember SUMIFS is not case sensitive—an advantage for most applications.

Example 2: Real-World Application

A regional marketing team tracks campaign spend in a table named [tblCampaigns]. Column [Campaign] contains combined tags such as “US-Email-Holiday”, “EU-Social-Promo”, “US-Social-Holiday”, and so on. Column [Spend] logs dollar amounts.

Business question: “How much did we spend on US campaigns that were also Social channel?”

  1. Ensure the table name [tblCampaigns] is correct (use Table Design > Table Name).
  2. In cell F3, type:
=SUMIFS(tblCampaigns[Spend], tblCampaigns[Campaign], "*US*", tblCampaigns[Campaign], "*Social*")
  1. Press Enter. The formula returns the combined spend from rows containing both tags.

Why this solves a real problem:

  • Management often needs quick cross-sections of data for reporting without re-importing into BI tools.
  • By embedding the formula in a dashboard, additional spend lines automatically update totals.

Integration tips:

  • Pair this with Data Validation lists so users pick “Region” and “Channel” from dropdowns, feeding the formula dynamically.
  • Feed the result into a chart or KPI card.

Performance considerations:

  • Wildcard searches on large tables (50k+ rows) remain fast with SUMIFS, but VC-based (volatile calculation) functions like INDIRECT can slow things down—avoid them inside SUMIFS criteria.
  • Storing the table on an Excel data model and referencing it with Cube functions can offload heavy lifting if totals become sluggish on older machines.

Example 3: Advanced Technique

Suppose you have a product database where sometimes the tags appear in mixed case and you must respect case sensitivity. Example descriptions might include “ProX-Lite” and “prox-lite” where only the exact uppercase “X” is meaningful legally. SUMIFS cannot discriminate by case, so you need a different approach.

Enter SUMPRODUCT with the FIND function, which is case sensitive:

  1. Data layout: Descriptions in [A2:A10000], quantities in [B2:B10000].
  2. Keywords are stored in cells D1 (exact “X”) and D2 (exact “Y”).
  3. In cell E1, enter:
=SUMPRODUCT((ISNUMBER(FIND(D1, A2:A10000)))*(ISNUMBER(FIND(D2, A2:A10000)))*B2:B10000)

Explanation of the logic:

  • FIND returns a number if it locates the substring; otherwise, it raises an error.
  • ISNUMBER converts that to TRUE or FALSE, which multiply as 1 or 0.
  • The two tests are multiplied together, enforcing AND logic.
  • Finally, the resulting array multiplies by the quantity column to yield the conditional sum.

Advanced points:

  • SUMPRODUCT handles arrays natively, so you do not need Control-Shift-Enter in modern Excel.
  • To optimize, limit the range to the used rows or convert to structured references for automatic resizing.
  • Wrap the formula in LET for readability and slightly better performance:
=LET(
 desc, A2:A10000,
 qty,  B2:B10000,
 k1,   D1,
 k2,   D2,
 sumArray, (ISNUMBER(FIND(k1, desc)))*(ISNUMBER(FIND(k2, desc)))*qty,
 SUM(sumArray)
)

Error handling: If a keyword cell is blank, the FIND function returns 1 on every row (because it finds empty text at position 1). Use IF(k\1=\"\",\"\", ... ) wrappers or Data Validation to force input.

Tips and Best Practices

  1. Use Tables and Structured References – Converting data to an Excel Table (Ctrl+T) keeps your ranges dynamic and eliminates manual ref updates.
  2. Store Keywords in Cells, Not Formulas – This supports ad-hoc analysis and reduces formula editing errors. Pair with Data Validation lists for consistency.
  3. Trim and Clean Source Text Early – A single invisible character can break wildcard matches. Apply CLEAN or SUBSTITUTE once in a helper column rather than repeatedly in your SUM functions.
  4. Avoid Volatile Functions Inside Criteria – Functions like TODAY inside the criteria can force full workbook recalculation; keep SUMIFS lean.
  5. Measure Performance – For datasets beyond 100k rows, try moving heavy calculations to Power Pivot or using PivotTables with slicers instead of thousands of on-sheet SUMIFS.
  6. Document Your Logic – Use comments or cell notes to explain why both X and Y matter—future maintainers will thank you.

Common Mistakes to Avoid

  1. Different Range Sizes – Mixing C2:C1000 with B2:B999 causes SUMIFS to return zero. Always verify matching endpoints or use Tables.
  2. Missing Wildcards – Writing \"*X\" instead of \"X\" enforces “ends with X” rather than “contains X.” Proof-read your criteria strings carefully.
  3. Case-Sensitive Assumptions – SUMIFS ignores case; analysts expecting case distinctions must switch to SUMPRODUCT+FIND.
  4. Accidental OR Logic – Some users write separate SUMIF formulas and add them together, double-counting rows that meet both conditions. Stick with a single multi-criteria approach for AND logic.
  5. Hidden Characters – Data imports from web pages can include non-breaking spaces. If results look wrong, inspect with LEN or CODE functions and remove problem characters.

Alternative Methods

While SUMIFS handles most needs, other methods offer specialized advantages.

MethodProsConsBest Use-Cases
SUMIFS with wildcardsFast, readable, backward compatibleNot case sensitiveMost day-to-day analysis, dashboards
SUMPRODUCT + FINDCase sensitive, supports arrays of keywordsSlightly slower, harder to readLegal labeling, SKU codes with exact casing
FILTER + SUMDynamic arrays, easy to spill filtered listOnly works in Excel 365/2021, version dependencyModern Excel users building interactive sheets
PivotTable with Label FiltersNo formulas, point-and-click interfaceManual refresh, less dynamic in formulasQuick ad-hoc exploration by non-formula users

When to migrate:

  • If you upgrade to Microsoft 365, consider FILTER to simplify formulas and enable spill ranges.
  • If workbook performance lags on older hardware with massive datasets, a PivotTable can cache data efficiently.
  • For advanced data models, push the logic into Power Query or DAX measures, then surface the result in a PivotTable or Power BI.

FAQ

When should I use this approach?

Use a multi-criteria SUMIFS whenever the AND condition applies to the same text cell and you only need partial text matches. It is ideal for keyword-tagged descriptions, combined codes, or multi-attribute product names.

Can this work across multiple sheets?

Yes. Point sum_range and criteria_range to qualified sheet references like Sheet2!B2:B100. If the ranges are on different sheets, both must use absolute references or defined names. SUMIFS can even reference closed workbooks as long as they have been opened once in the session.

What are the limitations?

SUMIFS is not case sensitive, cannot use regular expressions, and requires identical range sizes. If you need OR logic across multiple keywords or case precision, switch to SUMPRODUCT or Power Query.

How do I handle errors?

Wrap dynamic criteria in IFERROR to display blank strings when inputs are missing. Use Data Validation to prevent users from leaving keyword cells empty. For formulas that might reference empty tables, combine IF(COUNTA(range)=0,\"No data\",SUMIFS(...)) to avoid misleading zeros.

Does this work in older Excel versions?

SUMIFS is available from Excel 2007 onward. If you are on Excel 2003 or earlier, you must rely on SUMPRODUCT, which works in legacy versions but requires array formulas entered with Control-Shift-Enter.

What about performance with large datasets?

SUMIFS is optimized and multi-threaded, usually outperforming SUMPRODUCT. For sheets surpassing 100k rows or hosting dozens of SUMIFS, use Tables, keep ranges contiguous, avoid volatile functions, and consider moving heavy calculations to Power Pivot.

Conclusion

Mastering the ability to “sum if cells contain both X and Y” turns a potentially tedious filtering task into a single, auditable formula. Whether you rely on SUMIFS for speed and simplicity or leverage SUMPRODUCT and FILTER for special cases, the techniques covered here elevate your analytical toolkit. Incorporate them into dashboards, templates, and ad-hoc reports to save hours and prevent costly oversight. Next, experiment with combining these formulas with dropdown controls, conditional formatting, and PivotTables to create truly interactive Excel solutions. Happy analyzing!

We use tracking cookies to understand how you use the product and help us improve it. Please accept cookies to help us improve.