Excel count if text or text

COUNTIF function

Use COUNTIF, one of the statistical functions, to count the number of cells that meet a criterion; for example, to count the number of times a particular city appears in a customer list.

In its simplest form, COUNTIF says:

  • =COUNTIF(Where do you want to look?, What do you want to look for?)

For example:

  • =COUNTIF(A2:A5,»London»)

  • =COUNTIF(A2:A5,A4)

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

COUNTIF(range, criteria)

Argument name

Description

range    (required)

The group of cells you want to count. Range can contain numbers, arrays, a named range, or references that contain numbers. Blank and text values are ignored.

Learn how to select ranges in a worksheet.

criteria    (required)

A number, expression, cell reference, or text string that determines which cells will be counted.

For example, you can use a number like 32, a comparison like «>32», a cell like B4, or a word like «apples».

COUNTIF uses only a single criteria. Use COUNTIFS if you want to use multiple criteria.

Examples

To use these examples in Excel, copy the data in the table below, and paste it in cell A1 of a new worksheet.

Data

Data

apples

32

oranges

54

peaches

75

apples

86

Formula

Description

=COUNTIF(A2:A5,»apples»)

Counts the number of cells with apples in cells A2 through A5. The result is 2.

=COUNTIF(A2:A5,A4)

Counts the number of cells with peaches (the value in A4) in cells A2 through A5. The result is 1.

=COUNTIF(A2:A5,A2)+COUNTIF(A2:A5,A3)

Counts the number of apples (the value in A2), and oranges (the value in A3) in cells A2 through A5. The result is 3. This formula uses COUNTIF twice to specify multiple criteria, one criteria per expression. You could also use the COUNTIFS function.

=COUNTIF(B2:B5,»>55″)

Counts the number of cells with a value greater than 55 in cells B2 through B5. The result is 2.

=COUNTIF(B2:B5,»<>»&B4)

Counts the number of cells with a value not equal to 75 in cells B2 through B5. The ampersand (&) merges the comparison operator for not equal to (<>) and the value in B4 to read =COUNTIF(B2:B5,»<>75″). The result is 3.

=COUNTIF(B2:B5,»>=32″)-COUNTIF(B2:B5,»<=85″)

Counts the number of cells with a value greater than (>) or equal to (=) 32 and less than (<) or equal to (=) 85 in cells B2 through B5. The result is 1.

=COUNTIF(A2:A5,»*»)

Counts the number of cells containing any text in cells A2 through A5. The asterisk (*) is used as the wildcard character to match any character. The result is 4.

=COUNTIF(A2:A5,»?????es»)

Counts the number of cells that have exactly 7 characters, and end with the letters «es» in cells A2 through A5. The question mark (?) is used as the wildcard character to match individual characters. The result is 2.

Common Problems

Problem

What went wrong

Wrong value returned for long strings.

The COUNTIF function returns incorrect results when you use it to match strings longer than 255 characters.

To match strings longer than 255 characters, use the CONCATENATE function or the concatenate operator &. For example, =COUNTIF(A2:A5,»long string»&»another long string»).

No value returned when you expect a value.

Be sure to enclose the criteria argument in quotes.

A COUNTIF formula receives a #VALUE! error when referring to another worksheet.

This error occurs when the formula that contains the function refers to cells or a range in a closed workbook and the cells are calculated. For this feature to work, the other workbook must be open.

Best practices

Do this

Why

Be aware that COUNTIF ignores upper and lower case in text strings.


Criteria
aren’t case sensitive. In other words, the string «apples» and the string «APPLES» will match the same cells.

Use wildcard characters.

Wildcard characters —the question mark (?) and asterisk (*)—can be used in criteria. A question mark matches any single character. An asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) in front of the character.

For example, =COUNTIF(A2:A5,»apple?») will count all instances of «apple» with a last letter that could vary.

Make sure your data doesn’t contain erroneous characters.

When counting text values, make sure the data doesn’t contain leading spaces, trailing spaces, inconsistent use of straight and curly quotation marks, or nonprinting characters. In these cases, COUNTIF might return an unexpected value.

Try using the CLEAN function or the TRIM function.

For convenience, use named ranges

COUNTIF supports named ranges in a formula (such as =COUNTIF(fruit,»>=32″)-COUNTIF(fruit,»>85″). The named range can be in the current worksheet, another worksheet in the same workbook, or from a different workbook. To reference from another workbook, that second workbook also must be open.

Note: The COUNTIF function will not count cells based on cell background or font color. However, Excel supports User-Defined Functions (UDFs) using the Microsoft Visual Basic for Applications (VBA) operations on cells based on background or font color. Here is an example of how you can Count the number of cells with specific cell color by using VBA.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Get live and free answers on Excel

See also

COUNTIFS function

IF function

COUNTA function

Overview of formulas in Excel

IFS function

SUMIF function

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

In this example, the goal is to count cells in a range that contain text values. This could be hardcoded text like «apple» or «red», numbers entered as text, or formulas that return text values. Empty cells, and cells that contain numeric values or errors should not be included in the count. This problem can be solved with the COUNTIF function or the SUMPRODUCT function. Both approaches are explained below. For convenience, data is the named range B5:B15.

COUNTIF function

The simplest way to solve this problem is with the COUNTIF function and the asterisk (*) wildcard. The asterisk (*) matches zero or more characters of any kind. For example, to count cells in a range that begin with «a», you can use COUNTIF like this:

=COUNTIF(range,"a*") // begins with "a"

In this example however we don’t want to match any specific text value. We want to match all text values. To do this, we provide the asterisk (*) by itself for criteria. The formula in H5 is:

=COUNTIF(data,"*") // any text value

The result is 4, because there are four cells in data (B5:B15) that contain text values.

To reverse the operation of the formula and count all cells that do not contain text, add the not equal to (<>) logical operator like this:

=COUNTIF(data,"<>*") // non-text values

This is the formula used in cell H6. The result is 7, since there are seven cells in data (B5:B15) that do not contain text values.

COUNTIFS function

To apply more specific criteria, you can switch to the COUNTIFs function, which supports multiple conditions. For example, to count cells with text, but exclude cells that contain only a space character, you can use a formula like this:

=COUNTIFS(range,"*",range,"<> ")

This formula will count cells that contain any text value except a single space (» «).

SUMPRODUCT function

Another way to solve this problem is to use the SUMPRODUCT function with the ISTEXT function.  SUMPRODUCT makes it easy to perform a logical test on a range, then count the results. The test is performed with the ISTEXT function. True to its name, the ISTEXT function only returns TRUE when given a text value:

=ISTEXT("apple")// returns TRUE
=ISTEXT(70) // returns FALSE

To count cells with text values in the example shown, you can use a formula like this:

=SUMPRODUCT(--ISTEXT(data))

Working from the inside out, the logical test is based on the ISTEXT function:

ISTEXT(data)

Because data (B5:B15) contains 11 values, ISTEXT returns 11 results in an array like this:

{TRUE;TRUE;TRUE;FALSE;FALSE;TRUE;FALSE;FALSE;FALSE;FALSE;FALSE}

In this array, the TRUE values correspond to cells that contain text values, and the FALSE values represent cells that do not contain text. To convert the TRUE and FALSE values to 1s and 0s, we use a double negative (—):

--{TRUE;TRUE;TRUE;FALSE;FALSE;TRUE;FALSE;FALSE;FALSE;FALSE;FALSE}

The resulting array inside the SUMPRODUCT function looks like this:

=SUMPRODUCT({1;1;1;0;0;1;0;0;0;0;0}) // returns 4

With a single array to process, SUMPRODUCT sums the array and returns 4 as the result.

To reverse the formula and count all cells that do not contain text, you can nest the ISTEXT function inside the NOT function like this:

=SUMPRODUCT(--NOT(ISTEXT(data)))

The NOT function reverses the results from ISTEXT. The double negative (—) converts the array to numbers, and the array inside SUMPRODUCT looks like this:

=SUMPRODUCT({0;0;0;1;1;0;1;1;1;1;1}) // returns 7

The result is 7, since there are seven cells in data (B5:B15) that do not contain text values.

Note: the SUMPRODUCT formulas above may seem complex, but using Boolean operations in array formulas is powerful and flexible. It is also an important skill in modern functions like FILTER and XLOOKUP, which often use this technique to select the right data. The syntax used by COUNTIF on the other hand is unique to a group of eight functions and is therefore not as useful or portable.

Excel spreadsheet is known to be one of the best data storing and analyzing tools. Cells together make spreadsheets that consist of text and numbers. For more understanding, you have to differentiate cells filled with text.  

So, practically how would you count cells with text in Excel? You can use a few different formulas to count cells containing any text, empty cells, and cells with specific characters or just filtered cells. All these formulas can be used in Excel 2019, 2016, 2013, and 2010.  

At first, Excel spreadsheets were limited to dealing with numbers, however now we can use these sheets to store as well as modify text. Do you really want to know how many cells are filled with text in your data sheet?

For this purpose, you can use multiple functions in Excel. Depending on the situation, you can use any function.

Here you will find the tricks to count text in Excel. Let’s have a look at how you can count if a cell contains text in different conditions.

Before moving forward to learn how Excel counts cells with text, why not have a quick overview of what a Count If the function is.

COUNTIF Function

To be honest, counting cells containing text in a spreadsheet is not an easy task. That’s why the Count if the function is there to help you in this case. Using asterisk wildcards, you can count the number of cells having specific text with COUNTIF function.

The basic purpose of asterisk wildcards is to correspond to any characters or numbers. Putting them before and after any text, you can simply count the number of cells in which the text is found.  

Here is the general formula for the COUNTIF function:

=COUNTIF (Range, “*Text*”)

Example:

=COUNTIF (A2:A11, “*Class*”)

The last name “Class” when put in the asterisk, the COUNTIF formula simply calculates all string values within the range containing the name “Class.”

How to Count Number of Cells with Text in Excel

You can count if cell contains any text string or character by using two basic formulas.

Using COUNTIF Formula to Count All Cells with Text

The COUNTIF formula with an asterisk in the criteria argument is the main solution. For instance:

COUNTIF (range, “*”) (as mentioned above)

For more understanding of this formula, let’s have a look at which values are included and which are not:

Counted Values

  • Special characters
  • Cells with all kinds of text
  • Numbers formatted as text
  • Visually blank cells that have an empty string (“”), apostrophe (‘), space, or non-printing characters

Non-Counted Values

  • Numbers
  • Errors
  • Dates
  • Blank cells
  • Logical values of TRUE or FALSE

For instance, in the range A2:A10, you can count if the cell contains text, apart from dates, numbers, logical values, blank cells, and errors.

Try using one of the following formulas:

COUNTIF(A2:A10, “*”)

SUMPRODUCT(–ISTEXT(A2:A10))

SUMPRODUCT( ISTEXT(A2:A10)*1)

Count If Cell Contains Text without Spaces and Empty Strings

Using the above-mentioned formulas can help you count all cells containing any text or character in them. However, in some situations, it might be tiring and confusing as certain cells may look blank, but in reality, they are not.

Keep in mind that empty strings, spaces, apostrophes, line breaks, etc are not easily countable with the human eye. However, they are not difficult to count using formulas.

Using the COUNTIFS function will let you exclude “false positive” blank cells from the count. For instance, in the range A2:A7, you can count cells with text that overlooks the space character:

COUNTIFS(A2:A7l”*”A2:A7,”<>”)

If your target range has any formula-driven data, it might be possible that some of the formulas can ultimately be an empty string (“”). You can even ignore these empty strings by replacing “*” with “*?*” in the criteria 1 argument:

=COUNTIFS(A2:A9,”*?*”, A2:A9, “<>”)

Here the question mark shows that you need to have at least one text character. You know that an empty string does not have characters in it, and it does not meet that’s why it is not included. Also, remember that blank cells starting with an apostrophe (‘) are not included as well.

Below in the image, you can see a space in A7 cell, an apostrophe in A8, and an empty string (=””) in A9.  

How to Count IF Cells Contain Specific Text  

As you already know that COUNTIF function is best for counting all cells containing text, you can even COUNTIF cell contains specific text. Suppose, we need to count the number of times the word used “Excel” in a specific cell range:

  1. Open the spreadsheet in Excel you want to check.
  2. Click on a blank cell to enter the formula.

  1. In the blank cell, you need to type “=COUNTIF (range, criteria)”.

Using this formula will count all the number of cells having specific text within a cell range.

  1. You have to enter the cell range you need to count for the “range”. Now, add the first and last cells separated with a colon. Enter “A2: A20” to count cells.

  1. Now type “Excel” for the “Criteria.” It will help you count the number of cells using “Excel” in a certain range. Your formula will look like “=COUNTIF (A2:A20, “Excel”).

How To Count Cells with Color Text in Excel

Do you know Excel does not provide a formula to count cells with colored text?

However, still you cannot do this manually as counting all colored cells one by one is not an easy thing. By filtering the results, you can execute this process. Follow the steps given below:

  1. Go to the spreadsheet you want to analyze.

  1. Right-click a cell with the text of the color you want to count.

  1. Select “Filter,” and then “Filter by Selected Cell’s Font Color” to filter the cells with the selected text color.

  1. Get ready for counting the data range. Here is the formula if your text is from cell B2 to B20: “=SUBTOTAL (B2:B20)”

After pressing the “Enter” key, your filter will be applied and Excel will start showing the cells having that specific color and the remaining value–s will be hidden.

In the hidden rows, the “SUBTOTAL” function will not add the values. That’s why it will only count the selected color text.   

Summing Up Count If Cell Contains Text

For storing and analyzing the data, Excel is a huge platform that provides multiple functions for several problems. Both text and numbers are dealt in Excel. Around four hundred functions can use the COUNTIF function. It helps in finding the sum of cells containing specific data.  

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Вы можете использовать следующие методы для подсчета ячеек в Excel, содержащих определенный текст:

Метод 1: подсчет ячеек, содержащих один конкретный текст

=COUNTIF( A2:A13 , "*text*")

Эта формула будет подсчитывать количество ячеек в диапазоне A2:A13 , которые содержат «текст» в ячейке.

Метод 2: подсчет ячеек, содержащих один из нескольких текстов

=SUM(COUNTIF( A2:A13 ,{"*text1","*text2*","*text3*"}))

Эта формула будет подсчитывать количество ячеек в диапазоне A2:A13 , которые содержат «текст1», «текст2» или «текст3» в ячейке.

В следующих примерах показано, как использовать каждый метод на практике со следующим набором данных в Excel:

Пример 1. Подсчет ячеек, содержащих один конкретный текст

Мы можем использовать следующую формулу для подсчета значений в столбце Team , которые содержат «avs» в названии:

=COUNTIF( A2:A13 , "*avs*")

На следующем снимке экрана показано, как использовать эту формулу на практике:

Мы видим, что всего 4 ячейки в столбце « Команда » содержат «avs» в названии.

Пример 2. Подсчет ячеек, содержащих один из нескольких текстов

Мы можем использовать следующую формулу для подсчета количества ячеек в столбце Team , которые содержат «avs», «urs» или «pockets» в имени:

=SUM(COUNTIF( A2:A13 ,{"*avs","*urs*","*ockets*"}))

На следующем снимке экрана показано, как использовать эту формулу на практике:

Мы видим, что в общей сложности 7 ячеек в столбце « Команда » содержат «avs», «urs» или «pockets» в названии.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в Excel:

Excel: как удалить строки с определенным текстом
Excel: как проверить, содержит ли ячейка частичный текст
Excel: как проверить, содержит ли ячейка текст из списка

Microsoft Word allows you count text, but what about Excel? If you need a count of your text in Excel, you can get this by using the COUNTIF function and then a combination of other functions depending on your desired result. 

How to count text in Excel

If you want to learn how to count text in Excel, you need to use function COUNTIF with the criteria defined using wildcard *, with the formula: =COUNTIF(range;"*"). Range is defined cell range where you want to count the text in Excel and wildcard * is criteria for all text occurrences in the defined range.

Some interesting and very useful examples will be covered in this tutorial with the main focus on the COUNTIF function and different usages of this function in text counting. Limitations of COUNTIF function have been covered in this tutorial with an additional explanation of other functions such as SUMPRODUCT/ISNUMBER/FIND functions combination. After this tutorial, you will be able to count text cells in excel, count specific text cells, case sensitive text cells and text cells with multiple criteria defined – which is a very good base for further creative Excel problem-solving.                

Count Text Cells in Excel

Text Cells can be easily found in Excel using COUNTIF or COUNTIFS functions. The COUNTIF function searches text cells based on specific criteria and in the defined range. As in the example below, the defined range is table Name list, and text criteria is defined using wildcard “*”. The formula result is 5, all text cells have been counted. Note that number formatted as text in cell B10 is also counted, but Booleans (TRUE /FALSE) and error (#N/A) are not recognized as text.

The formula for counting text cells:

=COUNTIF(range;"*")

For counting non-text cells, the formula should be a little bit changed in criteria part:

=COUNTIF(range;"<>*")

If there are several criteria for counting cells, then COUNTIFS function should be used. For example, if we want to count the number of employees from Texas with project number greater than 20, then the function will look like:

=COUNTIFS(C3:C6;"Texas";D3:D6;">20").

In criteria range in column State, a specific text criteria is defined under quotations “Texas”. The second criteria is numeric, criteria range is column Number of projects, and criteria is numeric value greater than 20, also under quotations “>20”. If we were looking for exact value, the formula would look like:

=COUNTIFS(C3:C6;"Texas";D3:D6;20)

Count Specific Text in Cells

For counting specific text under cells range, COUNTIF function is suitable with the formula:

=COUNTIF(range;"*text*")

=COUNTIF(B3:B9;"*Mike*")

The first part of the formula is range and second is text criteria, in our example  “*Mike*”. If wildcard * has not been used before and after criteria text, formula result would have been 1 (Formula would find cells only with word Mike).  Wildcard * before and after criteria text, means that all cells that contain criteria characters will be taken into account. As in another example below with text criteria Sun, three cells were found (sun, Sunny, sun is shining)

=COUNTIF(B3:B10;"*Sun*")

Note: The COUNTIF function is not case sensitive, an alternative function for case sensitive text searches is SUMPRODUCT/FIND function combination.

Count Case Sensitive Specific Text

For a case-sensitive text count, a combination of three formulas should be used: SUMPRODUCT, ISNUMBER and FIND. Let’s look in the example below. If we want to count cells that contain text Sun, case sensitive, COUNTIF function would not be the appropriate solution, instead of this function combination of three functions mentioned above has to be used.

=SUMPRODUCT(--ISNUMBER(FIND("Sun";B3:B10)))

We should go through a separate function explanation in order to understand functions combination. FIND function, searches specific text in the defined cell, and returns the number of the starting position of the text used as criteria. This explanation is relevant, if the searching range is just one cell. If we want to use FIND function in a range of the cells, then the combination with SUMPRODUCT function is necessary.  

Without ISNUMBER, function combination of FIND and SUMPRODUCT functions would return an error. ISNUMBER function is necessary because whenever FIND function does not match defined criteria, the output will be an error, as in print screen below of the evaluated formula.

In order to change error values with Boolean TRUE/FALSE statement, ISNUMERIC formula should be used (defining numeric values as TRUE, and non-numeric as FALSE, as in print screen below).

You might be wondering what character in SUMPRODUCT function stands for. It converts Boolean values TRUE/FALSE in numeric values 1/0, enabling SUMPRODUCT function to deal with numeric operations (without character — in SUMPRODUCT function, the final result would be 0).

Remember, if you want to count specific text cells that are not case sensitive, COUNTIF function is suitable. For all case sensitive searches combination of SUMPRODUCT/ISNUMBER/FIND functions is appropriate.

Count Text Cells with Multiple Criteria

If you want to count cells with Multiple criteria, with all criteria acceptable, there is an interesting way of solving that problem, a combination of SUMPRODUCT/ISNUMBER/FIND functions. Please take a look in the example below. We should count all cells that contain either Mike or $. Tricky part could be the cells that contain both Mike and $.

=SUMPRODUCT(--(ISNUMBER(FIND("Mike";B3:B11))+ISNUMBER(FIND("$";B3:B11))>0))

Formula just looks complex, in order to be easier for understanding, I will divide it into several steps. Also, knowledge from the previous tutorial point will be necessary for further work, since the combination of FIND, ISNUMBER, and SUMPRODUCT functions have been explained.

In the first part of the function, we loop through the table and find cells that contain Mike:

=ISNUMBER(FIND("Mike";B3:B11))

The output of this part of the function will be an array with values  {1;0;0;0;1;0;0;0;1}, number 1, where criteria have been met, and 0, where has not.

In the second part of the function, looping criteria is $, counting cells containing this value:

=ISNUMBER(FIND("$";B3:B11))

The output of this part of the function will be an array with values  {1;0;0;1;1;0;0;0;1}, number 1, where criteria have been met, and 0, where has not.

Next step is to sum these two arrays, since cell should be counted if any of conditions is fulfilled:

=ISNUMBER(FIND("Mike";B3:B11))+ISNUMBER(FIND("$";B3:B11))

The output of this step is {2;0;0;1;2;0;0;0;2}, the number  greater than 0 means that one of the condition has been met (2 – both conditions, 1 – one condition)

Without function part >0, the final function would double count cells that met both conditions and the final result would be 7 (sum of all array numbers). In order to avoid it, in the formula should be added >0:

=ISNUMBER(FIND("Mike";B3:B11))+ISNUMBER(FIND("$";B3:B11))>0

The output of this step is array {1;0;0;1;1;0;0;0;1}, the previous array has been checked and only values greater than 0 are TRUE (in an array have value 1), and others are FALSE (in an array have value 0).

Final output of the formula is the sum of the final array values, 4.

Looks very confusing, but after several usages, you will become familiar with this functions.

At the end, we will cover one more multiple criteria text count function, already mentioned in the tutorial, COUNTIFS function. In order to distinguish the usage of functions mentioned above and COUNTIFS function, two words are enough OR/AND. If you want to count text cells with multiple criteria but all conditions have to be met at the same time, then COUNTIFS function is appropriate. If at least one condition should be met, then the combination of function explained above is suitable.

Look at the example below, the number of cells that contain both Mike and $ is easily calculated with COUNTIFS function:

=COUNTIFS(range1;"*text1*";range2;"*text2*")

=COUNTIFS(B3:B11;"*Mike*";B3:B11;"*$*")

In the defined range, function counts only cells where both conditions have been met. The final result is 3.

Still need some help with Excel formatting or have other questions about Excel? Connect with a live Excel expert here for some 1 on 1 help. Your first session is always free. 

Skip to content

СЧЕТЕСЛИ в Excel — примеры функции с одним и несколькими условиями

В этой статье мы сосредоточимся на функции Excel СЧЕТЕСЛИ (COUNTIF в английском варианте), которая предназначена для подсчета ячеек с определённым условием. Сначала мы кратко рассмотрим синтаксис и общее использование, а затем я приведу ряд примеров и предупрежу о возможных причудах при подсчете по нескольким критериям одновременно или же с определёнными типами данных.

По сути,они одинаковы во всех версиях, поэтому вы можете использовать примеры в MS Excel 2016, 2013, 2010 и 2007.

  1. Примеры работы функции СЧЕТЕСЛИ.
    • Для подсчета текста.
    • Подсчет ячеек, начинающихся или заканчивающихся определенными символами
    • Подсчет чисел по условию.
    • Примеры с датами.
  2. Как посчитать количество пустых и непустых ячеек?
  3. Нулевые строки.
  4. СЧЕТЕСЛИ с несколькими условиями.
    • Количество чисел в диапазоне
    • Количество ячеек с несколькими условиями ИЛИ.
  5. Использование СЧЕТЕСЛИ для подсчета дубликатов.
    • 1. Ищем дубликаты в одном столбце
    • 2. Сколько совпадений между двумя столбцами?
    • 3. Сколько дубликатов и уникальных значений в строке?
  6. Часто задаваемые вопросы и проблемы.

Функция Excel СЧЕТЕСЛИ применяется для подсчета количества ячеек в указанном диапазоне, которые соответствуют определенному условию.

Например, вы можете воспользоваться ею, чтобы узнать, сколько ячеек в вашей рабочей таблице содержит число, больше или меньше указанной вами величины. Другое стандартное использование — для подсчета ячеек с определенным словом или с определенной буквой (буквами).

СЧЕТЕСЛИ(диапазон; критерий)

Как видите, здесь только 2 аргумента, оба из которых являются обязательными:

  • диапазон — определяет одну или несколько клеток для подсчета. Вы помещаете диапазон в формулу, как обычно, например, A1: A20.
  • критерий — определяет условие, которое определяет, что именно считать. Это может быть числотекстовая строкассылка или выражение. Например, вы можете употребить  следующие критерии: «10», A2, «> = 10», «какой-то текст».

Что нужно обязательно запомнить?

  • В аргументе «критерий» условие всегда нужно записывать в кавычках, кроме случая, когда используется ссылка либо какая-то функция.
  • Любой из аргументов ссылается на диапазон из другой книги Excel, то эта книга должна быть открыта.
  • Регистр букв не учитывается.
  • Также можно применить знаки подстановки * и ? (о них далее – подробнее).
  • Чтобы избежать ошибок, в тексте не должно быть непечатаемых знаков.

Как видите, синтаксис очень прост. Однако, он допускает множество возможных вариаций условий, в том числе символы подстановки, значения других ячеек и даже другие функции Excel. Это разнообразие делает функцию СЧЕТЕСЛИ действительно мощной и пригодной для многих задач, как вы увидите в следующих примерах.

Примеры работы функции СЧЕТЕСЛИ.

Для подсчета текста.

Давайте разбираться, как это работает. На рисунке ниже вы видите список заказов, выполненных менеджерами. Выражение  =СЧЕТЕСЛИ(В2:В22,»Никитенко») подсчитывает, сколько раз этот работник присутствует в списке:

применение СЧЕТЕСЛИ

Замечание. Критерий не чувствителен к регистру букв, поэтому можно вводить как прописные, так и строчные буквы.

Если ваши данные содержат несколько вариантов слов, которые вы хотите сосчитать, то вы можете использовать подстановочные знаки для подсчета всех ячеек, содержащих определенное слово, фразу или буквы, как часть их содержимого.

К примеру, в нашей таблице есть несколько заказчиков «Корона» из разных городов. Нам необходимо подсчитать общее количество заказов «Корона» независимо от города.

=СЧЁТЕСЛИ(A2:A22;»*Коро*»)

Мы подсчитали количество заказов, где в наименовании заказчика встречается «коро» в любом регистре. Звездочка (*) используется для поиска ячеек с любой последовательностью начальных и конечных символов, как показано в приведенном выше примере. Если вам нужно заменить какой-либо один символ, введите вместо него знак вопроса (?).

Кроме того, указывать условие прямо в формуле не совсем рационально, так как при необходимости подсчитать какие-то другие значения вам придется корректировать её. А это не слишком удобно.

Рекомендуется условие записывать в какую-либо ячейку и затем ссылаться на нее. Так мы сделали в H9. Также можно употребить подстановочные знаки со ссылками с помощью оператора конкатенации (&). Например, вместо того, чтобы указывать «* Коро *» непосредственно в формуле, вы можете записать его куда-нибудь, и использовать следующую конструкцию для подсчета ячеек, содержащих «Коро»:

=СЧЁТЕСЛИ(A2:A22;»*»&H8&»*»)

Подсчет ячеек, начинающихся или заканчивающихся определенными символами

Вы можете употребить подстановочный знак звездочку (*) или знак вопроса (?) в зависимости от того, какого именно результата вы хотите достичь.

Если вы хотите узнать количество ячеек, которые начинаются или заканчиваются определенным текстом, независимо от того, сколько имеется других символов, используйте:

=СЧЁТЕСЛИ(A2:A22;»К*») — считать значения, которые начинаются с « К» .

=СЧЁТЕСЛИ(A2:A22;»*р») — считать заканчивающиеся буквой «р».

Если вы ищете количество ячеек, которые начинаются или заканчиваются определенными буквами и содержат точное количество символов, то поставьте вопросительный знак (?):

=СЧЁТЕСЛИ(С2:С22;»????д») — находит количество буквой «д» в конце и текст в которых состоит из 5 букв, включая пробелы.

= СЧЁТЕСЛИ(С2:С22,»??») — считает количество состоящих из 2 символов, включая пробелы.

Примечание. Чтобы узнать количество клеток, содержащих в тексте знак вопроса или звездочку, введите тильду (~) перед символом ? или *.

Например, = СЧЁТЕСЛИ(С2:С22,»*~?*») будут подсчитаны все позиции, содержащие знак вопроса в диапазоне С2:С22.

Подсчет чисел по условию.

В отношении чисел редко случается, что нужно подсчитать количество их, равных какому-то определённому числу. Тем не менее, укажем, что записать нужно примерно следующее:

= СЧЁТЕСЛИ(D2:D22,10000)

Гораздо чаще нужно высчитать количество значений, больших либо меньших определенной величины.

Чтобы подсчитать значения, которые большеменьше или равны указанному вами числу, вы просто добавляете соответствующий критерий, как показано в таблице ниже.

Обратите внимание, что математический оператор вместе с числом всегда заключен в кавычки .

критерии

 

Описание

Если больше, чем

=СЧЕТЕСЛИ(А2:А10;»>5″)

Подсчитайте, где значение больше 5.

Если меньше чем

=СЧЕТЕСЛИ(А2:А10;»>5″)

Подсчет со числами менее 5.

Если равно

=СЧЕТЕСЛИ(А2:А10;»=5″)

Определите, сколько раз значение равно 5.

Если не равно

=СЧЕТЕСЛИ(А2:А10;»<>5″)

Подсчитайте, сколько раз не равно 5.

Если больше или равно

=СЧЕТЕСЛИ(А2:А10;»>=5″)

Подсчет, когда больше или равно 5.

Если меньше или равно

=СЧЕТЕСЛИ(А2:А10;»<=5″)

Подсчет, где меньше или равно 5.

В нашем примере

=СЧЁТЕСЛИ(D2:D22;»>10000″)

Считаем количество крупных заказов на сумму более 10 000. Обратите внимание, что условие подсчета мы записываем здесь в виде текстовой строки и поэтому заключаем его в двойные кавычки.

Вы также можете использовать все вышеприведенные варианты для подсчета ячеек на основе значения другой ячейки. Вам просто нужно заменить число ссылкой.

Замечание. В случае использования ссылки, вы должны заключить математический оператор в кавычки и добавить амперсанд (&) перед ним. Например, чтобы подсчитать числа в диапазоне D2: D9, превышающие D3, используйте =СЧЕТЕСЛИ(D2:D9,»>»&D3)

Если вы хотите сосчитать записи, которые содержат математический оператор, как часть их содержимого, то есть символ «>», «<» или «=», то употребите в условиях подстановочный знак с оператором. Такие критерии будут рассматриваться как текстовая строка, а не числовое выражение.

Например, =СЧЕТЕСЛИ(D2:D9,»*>5*») будет подсчитывать все позиции в диапазоне D2: D9 с таким содержимым, как «Доставка >5 дней» или «>5 единиц в наличии».

Примеры с датами.

Если вы хотите сосчитать клетки с датами, которые больше, меньше или равны указанной вами дате, вы можете воспользоваться уже знакомым способом, используя формулы, аналогичные тем, которые мы обсуждали чуть выше. Все вышеприведенное работает как для дат, так и для чисел.

считаем количество дат

Позвольте привести несколько примеров:

критерии

 

Описание

Даты, равные указанной дате.

=СЧЕТЕСЛИ(E2:E22;»01.02.2019″)

Подсчитывает количество ячеек в диапазоне E2:E22 с датой 1 июня 2014 года.

Даты больше или равные другой дате.

=СЧЕТЕСЛИ(E2:E22,»>=01.02.2019″)

Сосчитайте количество ячеек в диапазоне E2:E22 с датой, большей или равной 01.06.2014.

Даты, которые больше или равны дате в другой ячейке, минус X дней.

=СЧЕТЕСЛИ(E2:E22,»>=»&H2-7)

Определите количество ячеек в диапазоне E2:E22 с датой, большей или равной дате в H2, минус 7 дней.

Помимо этих стандартных способов, вы можете употребить функцию СЧЕТЕСЛИ в сочетании с функциями даты и времени, например, СЕГОДНЯ(), для подсчета ячеек на основе текущей даты.

критерии

 

Равные текущей дате.

=СЧЕТЕСЛИ(E2:E22;СЕГОДНЯ())

До текущей даты, то есть меньше, чем сегодня.

=СЧЕТЕСЛИ(E2:E22;»<«&СЕГОДНЯ())

После текущей даты, т.е. больше, чем сегодня.

=СЧЕТЕСЛИ(E2:E22;»>»& ЕГОДНЯ ())

Даты, которые должны наступить через неделю.

= СЧЕТЕСЛИ(E2:E22,»=»&СЕГОДНЯ()+7)

В определенном диапазоне времени.

=СЧЁТЕСЛИ(E2:E22;»>=»&СЕГОДНЯ()+30)-СЧЁТЕСЛИ(E2:E22;»>»&СЕГОДНЯ())

Как посчитать количество пустых и непустых ячеек?

Посмотрим, как можно применить функцию СЧЕТЕСЛИ в Excel для подсчета количества пустых или непустых ячеек в указанном диапазоне.

Непустые.

В некоторых руководствах по работе с СЧЕТЕСЛИ вы можете встретить предложения для подсчета непустых ячеек, подобные этому:

СЧЕТЕСЛИ(диапазон;»*»)

Но дело в том, что приведенное выше выражение подсчитывает только клетки, содержащие любые текстовые значения. А это означает, что те из них, что включают даты и числа, будут обрабатываться как пустые (игнорироваться) и не войдут в общий итог!

Если вам нужно универсальное решение для подсчета всех непустых ячеек в указанном диапазоне, то введите:

СЧЕТЕСЛИ(диапазон;»<>» & «»)

Это корректно работает со всеми типами значений — текстом, датами и числами — как вы можете видеть на рисунке ниже.

подсчет пустых и непустых ячеек

Также непустые ячейки в диапазоне можно подсчитать:

=СЧЁТЗ(E2:E22).

Пустые.

Если вы хотите сосчитать пустые позиции в определенном диапазоне, вы должны придерживаться того же подхода — используйте в условиях символ подстановки для текстовых значений и параметр “” для подсчета всех пустых ячеек.

Считаем клетки, не содержащие текст:

СЧЕТЕСЛИ( диапазон; «<>» & «*»)

Поскольку звездочка (*) соответствует любой последовательности текстовых символов, в расчет принимаются клетки, не равные *, т.е. не содержащие текста в указанном диапазоне.

Для подсчета пустых клеток (все типы значений):

=СЧЁТЕСЛИ(E2:E22;»»)

Конечно, для таких случаев есть и специальная функция

=СЧИТАТЬПУСТОТЫ(E2:E22)

Но не все знают о ее существовании. Но вы теперь в курсе …

Нулевые строки.

Также имейте в виду, что СЧЕТЕСЛИ и СЧИТАТЬПУСТОТЫ считают ячейки с пустыми строками, которые только на первый взгляд выглядят пустыми.

Что такое эти пустые строки? Они также часто возникают при импорте данных из других программ (например, 1С). Внешне в них ничего нет, но на самом деле это не так. Если попробовать найти такие «пустышки» (F5 -Выделить — Пустые ячейки) — они не определяются. Но фильтр данных при этом их видит как пустые и фильтрует как пустые.

Дело в том, что существует такое понятие, как «строка нулевой длины» (или «нулевая строка»). Нулевая строка возникает, когда программе нужно вставить какое-то значение, а вставить нечего.

Проблемы начинаются тогда, когда вы пытаетесь с ней произвести какие-то математические вычисления (вычитание, деление, умножение и т.д.). Получите сообщение об ошибке #ЗНАЧ!. При этом функции СУММ и СЧЕТ их игнорируют, как будто там находится текст. А внешне там его нет.

И самое интересное — если указать на нее мышкой и нажать Delete (или вкладка Главная — Редактирование — Очистить содержимое) — то она становится действительно пустой, и с ней начинают работать формулы и другие функции Excel без всяких ошибок.

Если вы не хотите рассматривать их как пустые, используйте для подсчета реально пустых клеток следующее выражение:

=ЧСТРОК(E2:E22)*ЧИСЛСТОЛБ(E2:E22)-СЧЁТЕСЛИ(E2:E22;»<>»&»»)

что такое нулевые строки в Экселе

Откуда могут появиться нулевые строки в ячейках? Здесь может быть несколько вариантов:

  1. Он есть там изначально, потому что именно так настроена выгрузка и создание файлов в сторонней программе (вроде 1С). В некоторых случаях такие выгрузки настроены таким образом, что как таковых пустых ячеек нет — они просто заполняются строкой нулевой длины.
  2. Была создана формула, результатом которой стал текст нулевой длины. Самый простой случай:

=ЕСЛИ(Е1=1;10;»»)

В итоге, если в Е1 записано что угодно, отличное от 1, программа вернет строку нулевой длины. И если впоследствии формулу заменять значением (Специальная вставка – Значения), то получим нашу псевдо-пустую позицию.

Если вы проверяете какие-то условия при помощи функции ЕСЛИ и в дальнейшем планируете производить с результатами математические действия, то лучше вместо «» ставьте 0. Тогда проблем не будет. Нули всегда можно заменить или скрыть: Файл -Параметры -Дополнительно — Показывать нули в позициях, которые содержат нулевые значения.

СЧЕТЕСЛИ с несколькими условиями.

На самом деле функция Эксель СЧЕТЕСЛИ не предназначена для расчета количества ячеек по нескольким условиям. В большинстве случаев я рекомендую использовать его множественный аналог — функцию СЧЕТЕСЛИМН. Она как раз и предназначена для вычисления количества ячеек, которые соответствуют двум или более условиям (логика И). Однако, некоторые задачи могут быть решены путем объединения двух или более функций СЧЕТЕСЛИ в одно выражение.

Количество чисел в диапазоне

Одним из наиболее распространенных применений функции СЧЕТЕСЛИ с двумя критериями является определение количества чисел в определенном интервале, т.е. меньше X, но больше Y.

Например, вы можете использовать для вычисления ячеек в диапазоне B2: B9, где значение больше 5 и меньше или равно 15:

=СЧЁТЕСЛИ(B2:B11;»>5″)-СЧЁТЕСЛИ(B2:B11;»>15″)

Количество ячеек с несколькими условиями ИЛИ.

Когда вы хотите найти количество нескольких различных элементов в диапазоне, добавьте 2 или более функций СЧЕТЕСЛИ в выражение. Предположим, у вас есть список покупок, и вы хотите узнать, сколько в нем безалкогольных напитков.

Сделаем это:

=СЧЁТЕСЛИ(A4:A13;»Лимонад»)+СЧЁТЕСЛИ(A2:A11;»*сок»)

Обратите внимание, что мы включили подстановочный знак (*) во второй критерий. Он используется для вычисления количества всех видов сока в списке.

Как вы понимаете, сюда можно добавить и больше условий.

Использование СЧЕТЕСЛИ для подсчета дубликатов.

Другое возможное использование функции СЧЕТЕСЛИ в Excel — для поиска дубликатов в одном столбце, между двумя столбцами или в строке.

1. Ищем дубликаты в одном столбце

Эта простое выражение СЧЁТЕСЛИ($A$2:$A$24;A2)>1 найдет все одинаковые записи в A2: A24.

А другая формула СЧЁТЕСЛИ(B2:B24;ИСТИНА) сообщит вам, сколько существует дубликатов:

Для более наглядного представления найденных совпадений я использовал условное форматирование значения ИСТИНА.

2. Сколько совпадений между двумя столбцами?

Сравним список2 со списком1. В столбце Е берем последовательно каждое значение из списка2 и считаем, сколько раз оно встречается в списке1. Если совпадений ноль, значит это уникальное значение. На рисунке такие выделены цветом при помощи условного форматирования.

Выражение  =СЧЁТЕСЛИ($A$2:$A$24;C2) копируем вниз по столбцу Е.

Аналогичный расчет можно сделать и наоборот – брать значения из первого списка и искать дубликаты во втором.

Для того, чтобы просто определить количество дубликатов, можно использовать комбинацию функций СУММПРОИЗВ и СЧЕТЕСЛИ.

=СУММПРОИЗВ((СЧЁТЕСЛИ(A2:A24;C2:C24)>0)*(C2:C24<>»»))

Подсчитаем количество уникальных значений в списке2:

=СУММПРОИЗВ((СЧЁТЕСЛИ(A2:A24;C2:C24)=0)*(C2:C24<>»»))

Получаем 7 уникальных записей и 16 дубликатов, что и видно на рисунке.

Полезное. Если вы хотите выделить дублирующиеся позиции или целые строки, содержащие повторяющиеся записи, вы можете создать правила условного форматирования на основе формул СЧЕТЕСЛИ, как показано в этом руководстве — правила условного форматирования Excel.

3. Сколько дубликатов и уникальных значений в строке?

Если нужно сосчитать дубликаты или уникальные значения в определенной строке, а не в столбце, используйте одну из следующих формул. Они могут быть полезны, например, для анализа истории розыгрыша лотереи.

Считаем количество дубликатов:

=СУММПРОИЗВ((СЧЁТЕСЛИ(A2:K2;A2:K2)>1)*(A2:K2<>»»))

Видим, что 13 выпадало 2 раза.

Подсчитать уникальные значения:

=СУММПРОИЗВ((СЧЁТЕСЛИ(A2:K2;A2:K2)=1)*(A2:K2<>»»))

Часто задаваемые вопросы и проблемы.

Я надеюсь, что эти примеры помогли вам почувствовать функцию Excel СЧЕТЕСЛИ. Если вы попробовали какую-либо из приведенных выше формул в своих данных и не смогли заставить их работать или у вас возникла проблема, взгляните на следующие 5 наиболее распространенных проблем. Есть большая вероятность, что вы найдете там ответ или же полезный совет.

  1. Возможен ли подсчет в несмежном диапазоне клеток?

Вопрос: Как я могу использовать СЧЕТЕСЛИ для несмежного диапазона или ячеек?

Ответ: Она не работает с несмежными диапазонами, синтаксис не позволяет указывать несколько отдельных ячеек в качестве первого параметра. Вместо этого вы можете использовать комбинацию нескольких функций СЧЕТЕСЛИ:

Неправильно: =СЧЕТЕСЛИ(A2;B3;C4;»>0″)

Правильно: = СЧЕТЕСЛИ (A2;»>0″) + СЧЕТЕСЛИ (B3;»>0″) + СЧЕТЕСЛИ (C4;»>0″)

Альтернативный способ — использовать функцию ДВССЫЛ (INDIRECT) для создания массива из несмежных клеток. Например, оба приведенных ниже варианта дают одинаковый результат, который вы видите на картинке:

=СУММ(СЧЁТЕСЛИ(ДВССЫЛ({«B2:B11″;»D2:D11″});»=0»))

Или же

=СЧЕТЕСЛИ($B2:$B11;0) + СЧЕТЕСЛИ($D2:$D11;0)

  1. Амперсанд и кавычки в формулах СЧЕТЕСЛИ

Вопрос: когда мне нужно использовать амперсанд?

Ответ: Это, пожалуй, самая сложная часть функции СЧЕТЕСЛИ, что лично меня тоже смущает. Хотя, если вы подумаете об этом, вы увидите — амперсанд и кавычки необходимы для построения текстовой строки для аргумента.

Итак, вы можете придерживаться этих правил:

  • Если вы используете число или ссылку на ячейку в критериях точного соответствия, вам не нужны ни амперсанд, ни кавычки. Например:

= СЧЕТЕСЛИ(A1:A10;10) или = СЧЕТЕСЛИ(A1:A10;C1)

  • Если ваши условия содержат текст, подстановочный знак или логический оператор с числом, заключите его в кавычки. Например:

= СЧЕТЕСЛИ(A2:A10;»яблоко») или = СЧЕТЕСЛИ(A2:A10;»*») или = СЧЕТЕСЛИ(A2:A10;»>5″)

  • Если ваши критерии — это выражение со ссылкой или же какая-то другая функция Excel, вы должны использовать кавычки («») для начала текстовой строки и амперсанд (&) для конкатенации (объединения) и завершения строки. Например:

= СЧЕТЕСЛИ(A2:A10;»>»&D2) или = СЧЕТЕСЛИ(A2:A10;»<=»&СЕГОДНЯ())

Если вы сомневаетесь, нужен ли амперсанд или нет, попробуйте оба способа. В большинстве случаев амперсанд работает просто отлично.

Например, = СЧЕТЕСЛИ(C2: C8;»<=5″) и = СЧЕТЕСЛИ(C2: C8;»<=»&5) работают одинаково хорошо.

  1. Как сосчитать ячейки по цвету?

Вопрос: Как подсчитать клетки по цвету заливки или шрифта, а не по значениям?

Ответ: К сожалению, синтаксис функции не позволяет использовать форматы в качестве условия. Единственный возможный способ суммирования ячеек на основе их цвета — использование макроса или, точнее, пользовательской функции Excel VBA.

  1. Ошибка #ИМЯ?

Проблема: все время получаю ошибку #ИМЯ? Как я могу это исправить?

Ответ: Скорее всего, вы указали неверный диапазон. Пожалуйста, проверьте пункт 1 выше.

  1. Формула не работает

Проблема: моя формула не работает! Что я сделал не так?

Ответ: Если вы написали формулу, которая на первый взгляд верна, но она не работает или дает неправильный результат, начните с проверки наиболее очевидных вещей, таких как диапазон, условия, ссылки, использование амперсанда и кавычек.

Будьте очень осторожны с использованием пробелов. При создании одной из формул для этой статьи я был уже готов рвать волосы, потому что правильная конструкция (я точно знал, что это правильно!) не срабатывала. Как оказалось, проблема была на самом виду… Например, посмотрите на это: =СЧЁТЕСЛИ(A4:A13;» Лимонад»). На первый взгляд, нет ничего плохого, кроме дополнительного пробела после открывающей кавычки. Программа отлично проглотит всё без сообщения об ошибке, предупреждения или каких-либо других указаний. Но если вы действительно хотите посчитать товары, содержащие слово «Лимонад» и начальный пробел, то будете очень разочарованы….

Если вы используете функцию с несколькими критериями, разделите формулу на несколько частей и проверьте каждую из них отдельно.

И это все на сегодня. В следующей статье мы рассмотрим несколько способов подсчитывания ячеек в Excel с несколькими условиями.

Ещё примеры расчета суммы:

Skip to content

Excel Logo

Excel If Cell Contains Text

Excel If Cell Contains Text Then

Excel If Cell Contains Text Then Formula helps you to return the output when a cell have any text or a specific text. You can check if a cell contains a some string or text  and produce something in other cell. For Example you can check if a cell A1 contains text ‘example text’  and print Yes or No in Cell B1. Following are the example Formulas to check if Cell contains text then return some thing in a Cell.

If Cell Contains Text

Here are the Excel formulas to check if Cell contains specific text then return something. This will return if there is any string or any text in given Cell. We can use this simple approach to check if a cell contains text, specific text, string,  any text using Excel If formula. We can use equals to  operator(=) to compare the strings .

If Cell Contains Text Then TRUE

Following is the Excel formula to return True if a Cell contains Specif Text. You can check a cell if there is given string in the Cell and return True or False.

=IF(ISNUMBER(FIND(“How”,A1,1)),TRUE,FALSE)

The formula will return true if it found the match, returns False of no match found.

If Cell Contains Text Then TRUE

If Cell Contains Partial Text

We can return Text If Cell Contains Partial Text. We use formula or VBA to Check Partial Text in a Cell.

Find for Case Sensitive Match:

We can check if a Cell Contains Partial Text then return something using Excel Formula. Following is a simple example to find the partial text in a given Cell. We can use if your want to make the criteria case sensitive.

=IF(ISERROR(FIND($E$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text

  • Here, Find Function returns the finding position of the given string
  • Use Find function is Case Sensitive
  • IsError Function check if Find Function returns Error, that means, string not found

Search for Not Case Sensitive Match:

We can use Search function to check if Cell Contains Partial Text. Search function useful if you want to make the checking criteria Not Case Sensitive.

=IF(ISERROR(SEARCH($F$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text Not Case Sensitive

If Range of Cells Contains Text

We can check for the strings in a range of cells. Here is the formula to find If Range of Cells Contains Text. We can use Count If Formula to check the excel if range of cells contains specific text and return Text.

=IF(COUNTIF(A2:A21, “*Region 1d*”)>0,”Range Contais Text”,”Text Not Found in the Given Range”)
  • CountIf function counts the number of cells with given criteria
  • We can use If function to return the required Text
  • Formula displays the Text ‘Range Contains Text” if match found
  • Returns “Text Not Found in the Given Range” if match not found in the specified range

If Cells Contains Text From List

Below formulas returns text If Cells Contains Text from given List. You can use based on your requirement.

VlookUp to Check If Cell Contains Text from a List:
We can use VlookUp function to match the text in the Given list of Cells. And return the corresponding values.

  • Check if a List Contains Text:
    =IF(ISERR(VLOOKUP(F1,A1:B21,2,FALSE)),”False:Not Contains”,”True: Text Found”)
  • Check if a List Contains Text and Return Corresponding Value:
    =VLOOKUP(F1,A1:B21,2,FALSE)
  • Check if a List Contains Partial Text and Return its Value:
    =VLOOKUP(“*”&F1&”*”,A1:B21,2,FALSE)

If Cell Contains Text Then Return a Value

We can return some value if cell contains some string. Here is the the the Excel formula to return a value if a Cell contains Text. You can check a cell if there is given string in the Cell and return some string or value in another column.

If Cell Contains Text Then Return a Value

=IF(ISNUMBER(SEARCH(“How”,A1,1)),”Found”,”Not Found”)

The formula will return true if it found the match, returns False of no match found. can

Excel if cell contains word then assign value

You can replace any word in the following formula to check if cell contains word then assign value.

=IFERROR(IF(SEARCH(“Word”,A2,1)>0,1,0),””)

Excel if cell contains word then assign value
Search function will check for a given word in the required cell and return it’s position. We can use If function to check if the value is greater than 0 and assign a given value (example: 1) in the cell. search function returns #Value if there is no match found in the cell, we can handle this using IFERROR function.

Count If Cell Contains Text

We can check If Cell Contains Text Then COUNT. Here is the Excel formula to Count if a Cell contains Text. You can count the number of cells containing specific text.

=COUNTIF($A$2:$A$7,”*”&D2&”*”)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then COUNT

Count If Cell Contains Partial Text

We can count the cells based on partial match criteria. The following Excel formula Counts if a Cell contains Partial Text.

=COUNTIF(A2:A21, “*Region 1*”)
  • We can use the CountIf Function to Count the Cells if they contains given String
  • Wild-card operators helps to make the CountIf to check for the Partial String
  • Put Your Text between two asterisk symbols (*YourText*) to make the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to make the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to make the criteria to find your text end of given Cell

If Cell contains text from list then return value

Here is the Excel Formula to check if cell contains text from list then return value. We can use COUNTIF and OR function to check the array of values in a Cell and return the given Value. Here is the formula to check the list in range D2:D5 and check in Cell A2 and return value in B2.

=IF(OR(COUNTIF(A2,”*”&$D$2:$D$5&”*”)), “Return Value”, “”)

Excel If cell contains text from list then return value

If Cell Contains Text Then SUM

Following is the Excel formula to Sum if a Cell contains Text. You can total the cell values if there is given string in the Cell. Here is the example to sum the column B values based on the values in another Column.

=SUMIF($A$2:$A$7,”*”&D2&”*”,$B$2:$B$7)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then SUM

Sum If Cell Contains Partial Text

Use SumIfs function to Sum the cells based on partial match criteria. The following Excel formula Sums the Values if a Cell contains Partial Text.

=SUMIFS(C2:C21,A2:A21, “*Region 1*”)
  • SUMIFS Function will Sum the Given Sum Range
  • We can specify the Criteria Range, and wild-card expression to check for the Partial text
  • Put Your Text between two asterisk symbols (*YourText*) to Sum the Cells if the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to Sum the Cells if the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to Sum the Cells if criteria to find your text end of given Cell

VBA to check if Cell Contains Text

Here is the VBA function to find If Cells Contains Text using Excel VBA Macros.

If Cell Contains Partial Text VBA

We can use VBA to check if Cell Contains Text and Return Value. Here is the simple VBA code match the partial text. Excel VBA if Cell contains partial text macros helps you to use in your procedures and functions.

Sub sbCkeckforPartialText()
MsgBox CheckIfCellContainsPartialText(Cells(2, 1), “Region 1”)
End Sub
Function CheckIfCellContainsPartialText(ByVal cell As Range, ByVal strText As String) As Boolean
If InStr(1, cell.Value, strText) > 0 Then CheckIfCellContainsPartialText = True
End Function
  • CheckIfCellContainsPartialText VBA Function returns true if Cell Contains Partial Text
  • inStr Function will return the Match Position in the given string

If Cell Contains Text Then VBA MsgBox

Here is the simple VBA code to display message box if cell contains text. We can use inStr Function to search for the given string. And show the required message to the user.

Sub sbVBAIfCellsContainsText()
If InStr(1, Cells(2, 1), “Region 3”) > 0 Then blnMatch = True
If blnMatch = True Then MsgBox “Cell Contains Text”
End Sub
  • inStr Function will return the Match Position in the given string
  • blnMatch is the Boolean variable becomes True when match string
  • You can display the message to the user if a Range Contains Text

Which function returns true if cell a1 contains text?

You can use the Excel If function and Find function to return TRUE if Cell A1 Contains Text. Here is the formula to return True.

=IF(ISNUMBER(FIND(“YourText”,A1,1)),TRUE,FALSE)

Which function returns true if cell a1 contains text value?

You can use the Excel If function with Find function to return TRUE if a Cell A1 Contains Text Value. Below is the formula to return True based on the text value.

=IF(ISNUMBER(FIND(“YourTextValue”,A1,1)),TRUE,FALSE)

Share This Story, Choose Your Platform!

7 Comments

  1. Meghana
    December 27, 2019 at 1:42 pm — Reply

    Hi Sir,Thank you for the great explanation, covers everything and helps use create formulas if cell contains text values.

    Many thanks! Meghana!!

  2. Max
    December 27, 2019 at 4:44 pm — Reply

    Perfect! Very Simple and Clear explanation. Thanks!!

  3. Mike Song
    August 29, 2022 at 2:45 pm — Reply

    I tried this exact formula and it did not work.

  4. Theresa A Harding
    October 18, 2022 at 9:51 pm — Reply
  5. Marko
    November 3, 2022 at 9:21 pm — Reply

    Hi

    Is possible to sum all WA11?

    (A1) WA11 4

    (A2) AdBlue 1, WA11 223

    (A3) AdBlue 3, WA11 32, shift 4

    … and everything is in one column.

    Thanks you very much for your help.

    Sincerely Marko

  6. Mike
    December 9, 2022 at 9:59 pm — Reply

    Thank you for the help. The formula =OR(COUNTIF(M40,”*”&Vendors&”*”)) will give “TRUE” when some part of M40 contains a vendor from “Vendors” list. But how do I get Excel to tell which vendor it found in the M40 cell?

    • PNRao
      December 18, 2022 at 6:05 am — Reply

      Please describe your question more elaborately.
      Thanks!

© Copyright 2012 – 2020 | Excelx.com | All Rights Reserved

Page load link

Excel has many functions where a user needs to specify a single or multiple criteria to get the result. For example, if you want to count cells based on multiple criteria, you can use the COUNTIF or COUNTIFS functions in Excel.

This tutorial covers various ways of using a single or multiple criteria in COUNTIF and COUNTIFS function in Excel.

While I will primarily be focussing on COUNTIF and COUNTIFS functions in this tutorial, all these examples can also be used in other Excel functions that take multiple criteria as inputs (such as SUMIF, SUMIFS, AVERAGEIF, and AVERAGEIFS).

An Introduction to Excel COUNTIF and COUNTIFS Functions

Let’s first get a grip on using COUNTIF and COUNTIFS functions in Excel.

Excel COUNTIF Function (takes Single Criteria)

Excel COUNTIF function is best suited for situations when you want to count cells based on a single criterion. If you want to count based on multiple criteria, use COUNTIFS function.

Syntax

=COUNTIF(range, criteria)

Input Arguments

  • range –  the range of cells which you want to count.
  • criteria – the criteria that must be evaluated against the range of cells for a cell to be counted.

Excel COUNTIFS Function (takes Multiple Criteria)

Excel COUNTIFS function is best suited for situations when you want to count cells based on multiple criteria.

Syntax

=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…)

Input Arguments

  • criteria_range1 – The range of cells for which you want to evaluate against criteria1.
  • criteria1 – the criteria which you want to evaluate for criteria_range1 to determine which cells to count.
  • [criteria_range2] – The range of cells for which you want to evaluate against criteria2.
  • [criteria2] – the criteria which you want to evaluate for criteria_range2 to determine which cells to count.

Now let’s have a look at some examples of using multiple criteria in COUNTIF functions in Excel.

Using NUMBER Criteria in Excel COUNTIF Functions

#1 Count Cells when Criteria is EQUAL to a Value

To get the count of cells where the criteria argument is equal to a specified value, you can either directly enter the criteria or use the cell reference that contains the criteria.

Below is an example where we count the cells that contain the number 9 (which means that the criteria argument is equal to 9). Here is the formula:

=COUNTIF($B$2:$B$11,D3)

Using multiple criteria in Excel Functions - number equal to

In the above example (in the pic), the criteria is in cell D3. You can also enter the criteria directly into the formula. For example, you can also use:

=COUNTIF($B$2:$B$11,9)

#2 Count Cells when Criteria is GREATER THAN a Value

To get the count of cells with a value greater than a specified value, we use the greater than operator (“>”). We could either use it directly in the formula or use a cell reference that has the criteria.

Whenever we use an operator in criteria in Excel, we need to put it within double quotes. For example, if the criteria is greater than 10, then we need to enter “>10” as the criteria (see pic below):

Here is the formula:

=COUNTIF($B$2:$B$11,”>10″)

Using Multiple Criteria in Excel COUNTIF Function - Greater Than

You can also have the criteria in a cell and use the cell reference as the criteria. In this case, you need NOT put the criteria in double quotes:

=COUNTIF($B$2:$B$11,D3)

Using Multiple Criteria in Excel COUNTIF Function - - Greater Than criteria in cell reference

There could also be a case when you want the criteria to be in a cell, but don’t want it with the operator. For example, you may want the cell D3 to have the number 10 and not >10.

In that case, you need to create a criteria argument which is a combination of operator and cell reference (see pic below):

=COUNTIF($B$2:$B$11,”>”&D3)

Using Multiple Criteria in Excel COUNTIF Function - Greater Than operator and cell referenceNOTE: When you combine an operator and a cell reference, the operator is always in double quotes. The operator and cell reference are joined by an ampersand (&).

#3 Count Cells when Criteria is LESS THAN a Value

To get the count of cells with a value less than a specified value, we use the less than operator (“<“). We could either use it directly in the formula or use a cell reference that has the criteria.

Whenever we use an operator in criteria in Excel, we need to put it within double quotes. For example, if the criterion is that the number should be less than 5, then we need to enter “<5” as the criteria (see pic below):

=COUNTIF($B$2:$B$11,”<5″)

Using Multiple Criteria in Excel COUNTIF Function - less Than

You can also have the criteria in a cell and use the cell reference as the criteria. In this case, you need NOT put the criteria in double quotes (see pic below):

=COUNTIF($B$2:$B$11,D3)

Excel COUNTIF Function with multiple criteria - Less Than criteria in cell reference

Also, there could be a case when you want the criteria to be in a cell, but don’t want it with the operator. For example, you may want the cell D3 to have the number 5 and not <5.

In that case, you need to create a criteria argument which is a combination of operator and cell reference:

=COUNTIF($B$2:$B$11,”<“&D3)

Using Less Than operator in Excel COUNTIF function

NOTE: When you combine an operator and a cell reference, the operator is always in double quotes. The operator and cell reference are joined by an ampersand (&).

#4 Count Cells with Multiple Criteria – Between Two Values

To get a count of values between two values, we need to use multiple criteria in the COUNTIF function.

Here are two methods of doing this:

METHOD 1: Using COUNTIFS function

COUNTIFS function can handle multiple criteria as arguments and counts the cells only when all the criteria are TRUE. To count cells with values between two specified values (say 5 and 10), we can use the following COUNTIFS function:

=COUNTIFS($B$2:$B$11,”>5″,$B$2:$B$11,”<10″)

Using Multiple Criteria in Excel COUNTIFS Function - Between criteria

NOTE: The above formula does not count cells that contain 5 or 10. If you want to include these cells, use greater than equal to (>=) and less than equal to (<=) operators. Here is the formula:

=COUNTIFS($B$2:$B$11,”>=5″,$B$2:$B$11,”<=10″) 

You can also have these criteria in cells and use the cell reference as the criteria. In this case, you need NOT put the criteria in double quotes (see pic below):

Excel COUNTIFS Function with multiple criteria - Between criteria in cell references

You can also use a combination of cells references and operators (where the operator is entered directly in the formula). When you combine an operator and a cell reference, the operator is always in double quotes. The operator and cell reference are joined by an ampersand (&).

Excel COUNTIFS Function - Between criteria operator and cell references

METHOD 2: Using two COUNTIF functions

If you have multiple criteria, you can either use COUNTIFS or create a combination of COUNTIF functions. The formula below would also do the same thing:

=COUNTIF($B$2:$B$11,”>5″)-COUNTIF($B$2:$B$11,”>10″)

In the above formula, we first find the number of cells that have a value greater than 5 and we subtract the count of cells with a value greater than 10. This would give us the result as 5 (which is the number of cells that have values more than 5 and less than equal to 10).

Using Multiple Criteria in Excel COUNTIF Function - Between criteria two countif

If you want the formula to include both 5 and 10, use the following formula instead:

=COUNTIF($B$2:$B$11,”>=5″)-COUNTIF($B$2:$B$11,”>10″)

If you want the formula to exclude both ‘5’ and ’10’ from the counting, use the following formula:

=COUNTIF($B$2:$B$11,”>=5″)-COUNTIF($B$2:$B$11,”>10″)-COUNTIF($B$2:$B$11,10)

You can have these criteria in cells and use the cells references, or you can use a combination of operators and cells references.

Using TEXT Criteria in Excel Functions

#1 Count Cells when Criteria is EQUAL to a Specified text

To count cells that contain an exact match of the specified text, we can simply use that text as the criteria. For example, in the dataset (shown below in the pic), if I want to count all the cells with the name Joe in it, I can use the below formula:

=COUNTIF($B$2:$B$11,”Joe”)

Since this is a text string, I need to put the text criteria in double quotes.

Using Multiple Text Criteria in Excel COUNTIF Function

You can also have the criteria in a cell and then use that cell reference (as shown below):

=COUNTIF($B$2:$B$11,E3)

Using Multiple Text Criteria in Excel COUNTIFS Function

NOTE: You can get wrong results if there are leading/trailing spaces in the criteria or criteria range. Make sure you clean the data before using these formulas.

#2 Count Cells when Criteria is NOT EQUAL to a Specified text

Similar to what we saw in the above example, you can also count cells that do not contain a specified text. To do this, we need to use the not equal to operator (<>).

Suppose you want to count all the cells that do not contain the name JOE, here is the formula that will do it:

=COUNTIF($B$2:$B$11,”<>Joe”)

Using Multiple Criteria in Excel COUNTIF Function - Text criteria Not equal to

You can also have the criteria in a cell and use the cell reference as the criteria. In this case, you need NOT put the criteria in double quotes (see pic below):

=COUNTIF($B$2:$B$11,E3)

Using Multiple Criteria in Excel COUNTIF Function - Text criteria Not equal cells references

There could also be a case when you want the criteria to be in a cell but don’t want it with the operator. For example, you may want the cell D3 to have the name Joe and not <>Joe.

In that case, you need to create a criteria argument which is a combination of operator and cell reference (see pic below):

=COUNTIF($B$2:$B$11,”<>”&E3)

Using Multiple Criteria in Excel COUNTIF Function - Text criteria Not equal cells references and operator

When you combine an operator and a cell reference, the operator is always in double quotes. The operator and cell reference are joined by an ampersand (&).

Using DATE Criteria in Excel COUNTIF and COUNTIFS Functions

Excel store date and time as numbers. So we can use it the same way we use numbers.

#1 Count Cells when Criteria is EQUAL to a Specified Date

To get the count of cells that contain the specified date, we would use the equal to operator (=) along with the date.

To use the date, I recommend using the DATE function, as it gets rid of any possibility of error in the date value. So, for example, if I want to use the date September 1, 2015, I can use the DATE function as shown below:

=DATE(2015,9,1)

This formula would return the same date despite regional differences. For example, 01-09-2015 would be September 1, 2015 according to the  US date syntax and January 09, 2015 according to the UK date syntax. However, this formula would always return September 1, 2105.

Here is the formula to count the number of cells that contain the date 02-09-2015:

=COUNTIF($A$2:$A$11,DATE(2015,9,2))

Excel COUNTIF Function - Using multiple date criteria

#2 Count Cells when Criteria is BEFORE or AFTER to a Specified Date

To count cells that contain date before or after a specified date, we can use the less than/greater than operators.

For example, if I want to count all the cells that contain a date that is after September 02, 2015, I can use the formula:

=COUNTIF($A$2:$A$11,”>”&DATE(2015,9,2))

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria after

Similarly, you can also count the number of cells before a specified date. If you want to include a date in the counting, use and ‘equal to’ operator along with ‘greater than/less than’ operator.

You can also use a cell reference that contains a date. In this case, you need to combine the operator (within double quotes) with the date using an ampersand (&).

See example below:

=COUNTIF($A$2:$A$11,”>”&F3)

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria using cell reference and ampersand

#3 Count Cells with Multiple Criteria – Between Two Dates

To get a count of values between two values, we need to use multiple criteria in the COUNTIF function.

We can do this using two methods – One single COUNTIFS function or two COUNTIF functions.

METHOD 1: Using COUNTIFS function

COUNTIFS function can take multiple criteria as the arguments and counts the cells only when all the criteria are TRUE. To count cells with values between two specified dates (say September 2 and September 7), we can use the following COUNTIFS function:

=COUNTIFS($A$2:$A$11,”>”&DATE(2015,9,2),$A$2:$A$11,”<“&DATE(2015,9,7))

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria before and after

The above formula does not count cells that contain the specified dates. If you want to include these dates as well, use greater than equal to (>=) and less than equal to (<=) operators. Here is the formula:

=COUNTIFS($A$2:$A$11,”>=”&DATE(2015,9,2),$A$2:$A$11,”<=”&DATE(2015,9,7))

You can also have the dates in a cell and use the cell reference as the criteria. In this case, you can not have the operator with the date in the cells. You need to manually add operators in the formula (in double quotes) and add cell reference using an ampersand (&). See the pic below:

=COUNTIFS($A$2:$A$11,”>”&F3,$A$2:$A$11,”<“&G3)

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria before and after cell reference

METHOD 2: Using COUNTIF functions

If you have multiple criteria, you can either use one COUNTIFS function or create a combination of two COUNTIF functions. The formula below would also do the trick:

=COUNTIF($A$2:$A$11,”>”&DATE(2015,9,2))-COUNTIF($A$2:$A$11,”>”&DATE(2015,9,7))

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria before and after using countif without equal to

In the above formula, we first find the number of cells that have a date after September 2 and we subtract the count of cells with dates after September 7. This would give us the result as 7 (which is the number of cells that have dates after September 2 and on or before September 7).

If you don’t want the formula to count both September 2 and September 7, use the following formula instead:

=COUNTIF($A$2:$A$11,”>=”&DATE(2015,9,2))-COUNTIF($A$2:$A$11,”>”&DATE(2015,9,7))

Using Multiple Criteria in Excel COUNTIF Function - Date Criteria before and after using countif

If you want to exclude both the dates from counting, use the following formula:

=COUNTIF($A$2:$A$11,”>”&DATE(2015,9,2))-COUNTIF($A$2:$A$11,”>”&DATE(2015,9,7)-COUNTIF($A$2:$A$11,DATE(2015,9,7)))

Also, you can have the criteria dates in cells and use the cells references (along with operators in double quotes joined using ampersand).

Using WILDCARD CHARACTERS in Criteria in COUNTIF & COUNTIFS Functions

There are three wildcard characters in Excel:

  1. * (asterisk) – It represents any number of characters. For example, ex* could mean excel, excels, example, expert, etc.
  2. ? (question mark) – It represents one single character. For example, Tr?mp could mean Trump or Tramp.
  3. ~ (tilde) – It is used to identify a wildcard character (~, *, ?) in the text.

You can use COUNTIF function with wildcard characters to count cells when other inbuilt count function fails. For example, suppose you have a data set as shown below:

Count Cells that Contains Text in Excel Data Set

Now let’s take various examples:

#1 Count Cells that contain Text

To count cells with text in it, we can use the wildcard character * (asterisk). Since asterisk represents any number of characters, it would count all cells that have any text in it. Here is the formula:

=COUNTIFS($C$2:$C$11,”*”)

Using Multiple Criteria in Excel COUNTIF Function - wildcard character count text

Note: The formula above ignores cells that contain numbers, blank cells, and logical values, but would count the cells contain an apostrophe (and hence appear blank) or cells that contain empty string (=””) which may have been returned as a part of a formula.

Here is a detailed tutorial on handling cases where there is an empty string or apostrophe.

Here is a detailed tutorial on handling cases where there are empty strings or apostrophes.

Below is a video that explains different scenarios of counting cells with text in it.

#2 Count Non-blank Cells

If you are thinking of using COUNTA function, think again.

Try it and it might fail you. COUNTA will also count a cell that contains an empty string (often returned by formulas as =”” or when people enter only an apostrophe in a cell). Cells that contain empty strings look blank but are not, and thus counted by the COUNTA function.

COUNTA will also count a cell that contains an empty string (often returned by formulas as =”” or when people enter only an apostrophe in a cell). Cells that contain empty strings look blank but are not, and thus counted by the COUNTA function.

Count Cells that Contains Text in Excel Data Set

So if you use the formula =COUNTA(A1:A11), it returns 11, while it should return 10.

Here is the fix:

=COUNTIF($A$1:$A$11,”?*”)+COUNT($A$1:$A$11)+SUMPRODUCT(–ISLOGICAL($A$1:$A$11))

Let’s understand this formula by breaking it down:

#3 Count Cells that contain specific text

Let’s say we want to count all the cells where the sales rep name begins with J. This can easily be achieved by using a wildcard character in COUNTIF function. Here is the formula:

=COUNTIFS($C$2:$C$11,”J*”) 

Using Multiple Criteria in Excel COUNTIF Function - count specific text wildcard

The criteria J* specifies that the text in a cell should begin with J and can contain any number of characters.

If you want to count cells that contain the alphabet anywhere in the text, flank it with an asterisk on both sides. For example, if you want to count cells that contain the alphabet “a” in it, use *a* as the criteria.

This article is unusually long compared to my other articles. Hope you have enjoyed it. Let me know your thoughts by leaving a comment.

You May Also Find the following Excel tutorials useful:

  • Count the number of words in Excel.
  • Count Cells Based on Background Color in Excel.
  • How to Sum a Column in Excel (5 Really Easy Ways)

Понравилась статья? Поделить с друзьями:
  • Excel count if not value
  • Excel desktop что это
  • Excel count if not in range
  • Excel count if it contains
  • Excel delphi формула если