Excel count words in the cell

There is one option that I always wish Excel should have, and that is counting the number of words from a cell. If you work in MS Word there is an inbuilt option on the status bar which shows you how many words are there in the sheet.

there is an option in word to count words but not in excel

But when it comes to Excel there is no such option to count words. You can count the number of cells which have text but not actual words in them. As you know, in Excel, we have functions and you can use them to calculate almost everything. You can create a formula that can count words from a cell.

Today in this post, you will learn how to count words in Excel from a cell, a range of cells, or even the entire worksheet. And I’ll also show you how to count a specific word from a range of cells.

1. Count Words from a Single Cell

To count words from a cell you need to combine the LEN function with the SUBSTITUTE function. And the formula will be (Text is in cell A1):

=LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1

When you refer to a cell using this formula, it will return 7 in the result. And yes, you have a total of 7 words in the cell.

How it Works

Before getting into this formula just think this way. In a normal sentence if you have eight words then you will definitely have 7 spaces in those words. Right?

That means you will always have one word more than the spaces. The idea is simple: If you want to count the words, count the spaces and add one to them. To understand this formula you need to split it into three parts.

In the first part, you used the LEN function to count the number of characters from cell A1. And in the second and third parts, you have combined SUBSTITUTE with LEN to remove spaces from the cell and then count the characters. At this point, you have an equation like this.

The total number of characters with spaces and the total number of characters without spaces. And when you subtract both numbers get the number of spaces and in the end, you must add one to it. It returns 7 in the result which is the total number of words in the cell.

Important: When you use the above formula it will return 1 even if the cell is blank so it’s better to wrap it with the IF function to avoid this problem.

=IF(ISBLANK(A2),0,LEN(A2)-LEN(SUBSTITUTE(A2," ",""))+1)

This formula will first check the cell and only return the word count if there is a value in the cell.

2. Using a UDF

Apart from the above formulas, I have written a small code to create a UDF for this. This code will help you to create a custom function that will simply return the word count. In short, you don’t need to combine any functions.

Function MyWordCount(rng As Range) As Integer

MyWordCount = UBound(Split(rng.Value, " "), 1) + 1

End Function

Let me tell you how to use it.

  1. First of all, enter this code in VBA editor.
    add-udf-code-to-vbe-to-count-words-in-excel-cell
  2. And then come back to your worksheet, and enter “=MyWordCount(” and refer to the cell in which you have value.

And it will return the word count.

Related: Formula Bar in Excel

3. Count Words from a Range of Cells

Now let’s come to the next level. And here you need to count words from a range of cells instead of a single cell. The good news is you just need to use the same formula (just a simple change) which you have used above. And the formula will be:

=SUMPRODUCT(LEN(A1:A11)-LEN(SUBSTITUTE(A1:A11," ",""))+1)

In the above formula, A1:A11 is the range of cells and when you enter the formula it returns 77 in the result.

How it Works

This formula works in the same way as the first method works but is just a small advance. The only difference is you have wrapped it in SUMPRODUCT and referred to the entire range instead of a single cell.

Do you know that SUMPRODUCT can take arrays? So, when you use it, it returns an array where you have a count of words for each cell. And in the end, it sums those counts and tells you the count of words in the column.

4. Word Count from the Entire Worksheet

This code is one of the useful macro codes which I use in my work, and it can help you to count all the words from a worksheet.

Sub Word_Count_Worksheet()

Dim WordCnt As Long
Dim rng As Range
Dim S As String
Dim N As Long

For Each rng In ActiveSheet.UsedRange.Cells
S = Application.WorksheetFunction.Trim(rng.Text)
N = 0

If S <> vbNullString Then
N = Len(S) – Len(Replace(S, " ", "")) + 1
End If

WordCnt = WordCnt + N

Next rng

MsgBox "There are total " & Format(WordCnt, "#,##0") & " words in the active worksheet"

End Sub

When you run it, it will show a message box with the number of words you have in the active worksheet.

Related: What is VBA in Excel

5. Count a Specific Word/Text String from a Range

Here you have a different situation. Let’s say you need to count a specific word from a range of cells or check the number of times a value appears in a column.

Take this example: Below you have a range of four cells and from this range, you need to count the count of occurrences of the word “Monday”.

For this, the formula is:

=SUMPRODUCT((LEN(D6:D9)-LEN(SUBSTITUTE(D6:D9,"Monday","")))/LEN("Monday"))

And when you enter it, it returns to the count of the word “Monday”. That’s 4.

Important: It returns the count of the word (word’s frequency) from the range not the count of the cells which have that word. Monday is there four times in three cells.

How it Works

To understand this function, again you need to split it into four parts. In the first part, the LEN function returns an array of the count of characters from the cells.

The second part returns an array of the count of characters from the cells by removing the word “Monday”.

In the third part, the LEN function returns the length of characters of wor word “Monday”.

After that, subtracts part one from part two and then divides it with part three it returns an array with the count of the word “Monday” from each cell.

In the fourth part, SUMPRODUCT returns the sum of this array and gives the count of “Monday” from the range.

Download Sample File

  • Ready

Conclusion

Whenever you are typing some text in a cell or a range of cells you can these methods to keep a check on the word count. I wish someday in the future Excel will get this option to count words. But, for the time being, you have all these awesome methods.

Which method do you like the most? Make sure to share your views with me in the comment section, I’d love to hear from you. And please, don’t forget to share this post with your friends, I am sure they will appreciate it.

Excel doesn’t have a dedicated function for counting words in a cell. However, with a little ingenuity, you can create such a formula using the SUBSTITUTE and LEN functions, with help from TRIM, as shown in the example. At a high level, this formula uses the LEN function to count the number of characters in the cell, with and without spaces, then uses the difference to figure out the word count. This works, because word count is equal to the number of spaces + 1, so long as there is one space between each word.

The first part of the formula counts the characters in cell B5, after removing extra space:

=LEN(TRIM(B5)) // normalize space, count characters

Inside LEN, the TRIM function first removes any extra spaces between words, or at the beginning or end of the text. This is important, since any extra spaces will throw off the word count. In this case, there are no extra space characters, so TRIM returns the original text directly to the LEN function, which returns 30:

LEN("All Quiet on the Western Front") // returns 30

At this point, we have:

=30-LEN(SUBSTITUTE(B5," ",""))+1

Next, we use the SUBSTITUTE function to remove all space characters from the text:

SUBSTITUTE(B5," ","") // strip all space

Notice SUBSTITUTE is configured to look for a space character (» «), and replace with an empty string («»). By default, SUBSTITUTE will replace all spaces. The result is delivered directly to the LEN function, which returns the count:

LEN("AllQuietontheWesternFront") // returns 25

LEN returns 25, the number of characters remaining after all space has been removed. We can now simplify the formula to:

=30-25+1 // returns 6

which returns 6 as a final result, the number of words in cell B5.

Dealing with blank cells

The formula in the example will return 1 even if a cell is empty, or contains only space. This happens because we are adding 1 unconditionally, after counting space characters between words. To guard against this problem, you can adapt the formula as shown below:

=LEN(TRIM(B5))-LEN(SUBSTITUTE(B5," ",""))+(LEN(TRIM(B5))>0)

Notice we’ve replaced 1 with this expression:

LEN(TRIM(B5))>0

This code first trims B5, then checks the length. If B5 contains text, LEN returns a positive number, and the expression returns TRUE. If B5 is empty, or contains only space, TRIM returns an empty string («») to LEN. In that case, LEN returns zero (0) and the expression returns FALSE. The trick is that TRUE and FALSE evaluate to 1 and zero, respectively, when involved in any math operation. As a result, the expression only adds 1 when there is text in B5. Otherwise, it adds zero (0). This logic could also be written with the IF function statement like this:

IF(LEN(TRIM(B5))>0,1,0)

and the result would be the same. The expression above is simply more compact.

Count Words in a Cell of Excel

There is no in-built excel formula to find the Word Count and therefore, it needs to be entered manually. You can make use of the formula below to calculate wordcount in excel –

=LEN(TRIM(cell))-LEN(SUBSTITUTE(cell,” “,””))+1

Let us understand the working of this formula.

To begin with, we utilize the SUBSTITUTE functionSubstitute function in excel is a very useful function which is used to replace or substitute a given text with another text in a given cell, this function is widely used when we send massive emails or messages in a bulk, instead of creating separate text for every user we use substitute function to replace the information.read more to evacuate and displace all spaces in the cell with a vacant content string (“). The LEN functionThe Len function returns the length of a given string. It calculates the number of characters in a given string as input. It is a text function in Excel as well as an inbuilt function that can be accessed by typing =LEN( and entering a string as input.read more restores the length of the string without spaces.

Next, we subtract the string length without spaces from the absolute length of the string. The number of words in a cell is equivalent to the number of spaces plus 1. So, we add 1 to the word count.

Further, we utilize the TRIM functionThe Trim function in Excel does exactly what its name implies: it trims some part of any string. The function of this formula is to remove any space in a given string. It does not remove a single space between two words, but it does remove any other unwanted spaces.read more to remove extra spaces in a cell. A worksheet may contain a lot of imperceptible spaces. Such coincidental occurrence might be towards the start or end of the text (leading and trailing spaces). Since extra spaces return an incorrect word count, the TRIM function is used before computing the length of the string.

The steps to count the total number of words in a cell of Excel are listed as follows:

  1. Select the cell in the Excel sheet where you want the result to appear.

    Word-Count-Example-1

  2. For counting the number of words in cell A1, enter the formula shown in the following image.

    Word-Count-Example-1-1-1

  3. Click “Enter” and the exact number of words appear in cell B1.

    Word-Count-Example-1-2

Table of contents
  • Count Words in a Cell of Excel
    • How to Count the Total Number of Words in a Range of Cells?
    • How to Count Specific Words in a Range?
    • Frequently Asked Questions
    • Recommended Articles

How to Count the Total Number of Words in a Range of Cells?

To count the number of words in a range of cells, apply the equation that counts the words in a cell and implant it either inside the SUM or the SUMPRODUCT function.

The formula to count words of a particular range is “=LEN(TRIM(cell))-LEN(SUBSTITUTE(cell,” “,””))+1.”

  • Step 1: Select the range of data whose words you wish to count.

Word Count Example 2

  • Step 2: Enter the formula in the cell where you want the result to display as shown in the succeeding image.

Word Count Example 2-1

  • Step 3: Click “Enter” and the result appears in cell B1.

Example 2-2

  • Step 4: Drag the fill handle to all cells to get the word count of each cell in Excel.

Example 2-3

How to Count Specific Words in a Range?

To count the number of times a specific word appears in a range of cells, we utilize a comparative methodology. We count the explicit words in a cell and consolidate it with the SUM or SUMPRODUCT functionThe SUMPRODUCT excel function multiplies the numbers of two or more arrays and sums up the resulting products.read more.

  • Step 1: Select the cell and enter the formula “=(LEN(cell)-LEN(SUBSTITUTE(cell,word,””)))/LEN(word)” as shown in the following image.

Example 4

  • Step 2: Click “Enter” to see the word count in cell A14. The formula we used above helps us know the number of times the word “February” is present in cell A2.

The result in cell A14 is 4.

Example 4-1

Frequently Asked Questions

#1 – How to count the number of times a single character appears in a cell?

The formula to count the occurrence of a single character in a cell is stated as follows:
=LEN(cell_ref)-LEN(SUBSTITUTE(cell_ref,”a”,””))

The “cell_ref” stands for cell reference. The letter “a” stands for the character that the user wants to count.

#2 – How to count the number of times a single character appears in a range of cells?

The formula to count the occurrence of a single character in a range of cells is stated as follows:

=SUM(LEN(range)-LEN(SUBSTITUTE(range,”a”2,””)))

The “range” stands for the range of cells to which the formula is applied. The letter “a” stands for the character that the user wants to count.

#3 – How to count the number of times a specific word appears in a row or a column?

The steps to count the number of times a particular word appears in a row or a column are listed as follows:

1- Select the row or the column in which the word is to be counted. The row is selected by clicking the number on the left-hand side. The column is selected by clicking the letter that appears on top of the column.
2 – In the formula tab, click “Define Name” and enter a name for the row or the column in the “New Name” box.
3 – If the column is named “NamesColumn,” the cells in this column will use “NamesColumn” for reference.
4 – Apply the formula “=COUNTIF(NamesColumn,”Jack”)” to count the number of times “Jack” appears in the “NamesColumn.”

Note: Every time a new name is added to a cell of “NamesColumn,” the result of the formula will automatically update.

  • The formula to count words of a particular range is “=LEN(TRIM(cell))-LEN(SUBSTITUTE(cell,” “,””))+1.”
  • The word count formula is combined with the SUM or SUMPRODUCT function to handle arrays.
  • The SUBSTITUTE function replaces all the spaces of the cell with a vacant content string (“).
  • The LEN function restores the length of the string without spaces.
  • The TRIM function removes the leading and trailing spaces found at the beginning or at the end of the text.
  • The number of words in a cell is equivalent to the number of spaces plus 1.

Recommended Articles

This has been a guide to Word Count in Excel. Here we discuss how to count the total number of words in a cell and an excel range along with practical examples and a downloadable template. You may learn more about Excel from the following articles –

  • Count Rows in Excel | ExamplesThere are numerous ways to count rows in Excel using the appropriate formula, whether they are data rows, empty rows, or rows containing numerical/text values. Depending on the circumstance, you can use the COUNTA, COUNT, COUNTBLANK, or COUNTIF functions.read more
  • Count Colored Cells In ExcelTo count coloured cells in excel, there is no inbuilt function in excel, but there are three different methods to do this task: By using Auto Filter Option, By using VBA Code, By using FIND Method.
    read more
  • Excel Count FormulaThe COUNT function in excel counts the number of cells containing numerical values within the given range. It is a statistical function and returns an integer value. The syntax of the COUNT formula is “=COUNT(value 1, [value 2],…)”
    read more
  • How to Count Unique Values in Excel?In Excel, there are two ways to count values: 1) using the Sum and Countif function, and 2) using the SUMPRODUCT and Countif function.read more
  • Compare Two Lists in ExcelThe five different methods used to compare two lists of a column in excel are — Compare Two Lists Using Equal Sign Operator, Match Data by Using Row Difference Technique, Match Row Difference by Using IF Condition, Match Data Even If There is a Row Difference, Partial Matching Technique.read more

no-override

Reader Interactions

На чтение 6 мин. Просмотров 17.5k.

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

Если вы работаете в MS Word, в строке состояния есть встроенная опция, которая показывает, сколько слов на листе.

строка состояния Word

В Word есть опция для подсчета слов, но не в Excel. Вы можете посчитать количество ячеек, в которых есть текст, но не фактические слова в них.

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

Содержание

  1. Четыре разных способа посчитать слова в Excel
  2. 1. Формула для подсчета слов в ячейке
  3. 2. Подсчет слов в диапазоне ячеек
  4. 3. Подсчет количества слов во всей таблицы с кодом VBA
  5. 4. Подсчет определенного слова/текстовой строки в диапазоне
  6. Заключение

Четыре разных способа посчитать слова в Excel

Сегодня в этой статье вы научитесь считать слова в Excel в ячейке или диапазоне ячеек или даже во всей таблице.

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

1. Формула для подсчета слов в ячейке

Сочетание функций ДЛСТР с ПОДСТАВИТЬ

И формула будет (текст в ячейке A1):

= ДЛСТР(A1) — ДЛСТР (ПОДСТАВИТЬ (A1; » «; «»)) + 1

Когда вы ссылаетесь на ячейку, используя эту формулу, она вернет 5 в результате.

Пример работы формулы

И да, у вас есть 5 слов в ячейке.

Как формула работает?

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

Идея проста: если вы хотите посчитать слова, подсчитайте пробелы и добавьте единицу.

Теперь, чтобы понять эту формулу, вам нужно разделить ее на три части.

Разделение формулы на части

В первой части мы использовали функцию ДЛСТР (LEN) для подсчета количества символов в ячейке A1. А во второй и третьей части мы объединили ПОДСТАВИТЬ (SUBSTITUTE) с ДЛСТР (LEN), чтобы удалить пробелы из ячейки и затем подсчитать символы.

Наше уравнение выглядит так:

= 20 — 16 +1

  • 20 — общее количество символов с пробелами
  • 16 — символы без пробелов

Когда вы вычтете одно из другого, вы получите количество пробелов, и вам останется добавить один. В результате возвращается число 5, что является общим количеством слов в ячейке.

Когда вы используете приведенную выше формулу, она вернет 1, даже если ячейка пуста, поэтому лучше обернуть ее функцией ЕСЛИ (IF), чтобы избежать этой проблемы.

= ЕСЛИ(ЕПУСТО (A1);0; ДЛСТР(A1) — ДЛСТР(ПОДСТАВИТЬ(A1; » «; «»)) + 1)

Эта формула сначала проверяет ячейку и возвращает количество слов, только если в ячейке есть значение.

Как посчитать слова в Excel

Пользовательская функция

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

Function MyWordCount(rng As Range) As Integer

MyWordCount = UBound(Split(rng.Value, " "), 1) + 1

End Function

Давайте я расскажу вам, как ее использовать.

  • Прежде всего, введите этот код в редакторе VBA.
Введите формулу в редактор
  • Затем вернитесь на свой рабочий лист и введите «= MyWordCount(» и сошлитесь на ячейку, в которой у вас есть значение.

И она вернет количество слов.

Работа пользовательской функции

2. Подсчет слов в диапазоне ячеек

Теперь давайте перейдем на следующий уровень. Здесь вам нужно будет посчитать слова уже в диапазоне ячеек вместо одной ячейки.

Хорошая новость! Можно использовать ту же формулу (добавив небольшое изменение), которую мы использовали выше.

Вот эта формула:

= СУММПРОИЗВ(ДЛСТР(A1:A11)-ДЛСТР(ПОДСТАВИТЬ(A1:A11; » «;»»))+1)

Работа формулы подсчета слов в диапазоне

В приведенной выше формуле A1: A11 — это диапазон ячеек, при вводе формулы в результате получим 55.

Как это работает?

Эта формула работает так же, как и первый метод, но только чуть сложнее. Разница лишь в том, что мы завернули ее в СУММПРОИЗВ (SUMPRODUCT) и ссылаемся на весь диапазон вместо одной ячейки.

Расшифровка работы функции

Вы помните, что СУММПРОИЗВ (SUMPRODUCT) может работать с массивами? Поэтому, когда вы используете эту функцию, она возвращает массив, в котором у вас есть количество слов для каждой ячейки. Далее она суммирует эти цифры и сообщает вам количество слов в столбце.

3. Подсчет количества слов во всей таблицы с кодом VBA

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

Sub Word_Count_Worksheet()

Dim WordCnt As Long

Dim rng As Range

Dim S As String

Dim N As Long

For Each rng In ActiveSheet.UsedRange.Cells

S = Application.WorksheetFunction.Trim(rng.Text)

N = 0

If S <> vbNullString Then

N = Len(S) - Len(Replace(S, " ", "")) + 1

End If

WordCnt = WordCnt + N

Next rng

MsgBox "Всего " & Format(WordCnt, "#,##0") & " слов на активном листе"

End Sub

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

Демонстрация работы макроса

4. Подсчет определенного слова/текстовой строки в диапазоне

Здесь у нас другая ситуация. Допустим, нам нужно посчитать определенное слово в диапазоне ячеек или проверить, сколько раз значение появляется в столбце.

Разберем на примере.

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

Вот формула для этого:

= СУММПРОИЗВ ((ДЛСТР (A1:A4) — ДЛСТР (ПОДСТАВИТЬ (A1:A4; «понедельник»; «»)) / ДЛСТР(«понедельник»))

Формула подсчета конкретного слова

И когда вы введете ее, она возвратит количество понедельников. Ответ — 4.

Формула возвращает количество слов (частоту слова) в диапазоне, а не количество ячеек, в которых есть это слово.

Понедельник встречается четыре раза в трех ячейках.

Как это работает?

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

В первой части функция ДЛСТР (LEN) возвращает массив количества символов в ячейках.

Работа первой части формулы

Вторая часть возвращает массив подсчета символов в ячейках, удалив слово «понедельник».

Работа второй части формулы

В третьей части функция ДЛСТР (LEN) возвращает длину символов слова «понедельник».

Работа третьей части формулы

После этого вычитаем первую часть из второй, а затем делим ее на третью часть. Возвращен массив с количеством слов «понедельник» в каждой ячейке.

Работа четвертой части формулы

В четвертой части СУММПРОИЗВ (SUMPRODUCT) возвращает сумму этого массива и дает количество понедельников в диапазоне.

Заключение

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

Я мечтаю, что когда-нибудь в будущем в Excel появится эта опция. Ну а пока будем пользоваться этими замечательными методами.

Я надеюсь, что статья была полезной для вас. Какой метод вам понравился больше всех?

Не забудьте поделиться своими мнениями со мной в разделе комментариев, для меня это важно. И, пожалуйста, не забудьте поделиться со своими друзьями, я уверен, что они это оценят.

Return to Excel Formulas List

Download Example Workbook

Download the example workbook

This tutorial will teach you how to count words in a cell in Excel and Google Sheets.

count words in cell Main Function

Counting Words

There is no built-in Excel function to count the number of words in a cell. However, we can count the number of spaces, which can tell us how many words are in a cell:

=LEN(TRIM(B3))-LEN(SUBSTITUTE(B3," ",""))+1

count words in cell EX 01

Let’s see how this formula works.

Remove All Spaces

First, we use SUBSTITUTE Function to remove all spaces from the text string.

=SUBSTITUTE(B3," ","")

count words in cell EX 02

Then we determine the length of this space-free string with the LEN Function.

=LEN(C3) or =LEN(SUBSTITUTE(B3," ",""))

count words in cell EX 03

We will compare the string length before and after removing the spaces, to count how many spaces the cell contains.

Remove Extra Spaces

Next, we want to express this string as we normally would (i.e. containing only single spaces between words). The TRIM function removes extra spaces from a text string, leaving a single spaces between each word, so all leading, trailing, and repeated spaces will be excluded.

=TRIM(B3)

count words in cell EX 04

Then we determine the length of this normally-arranged text with the LEN function.

=LEN(E3) or =LEN(TRIM(B3))

count words in cell EX 05

Finding the different between the two lengths (with and without spaces) and adding one (since there is no space after the last word) gives us the word count of the cell:

=F3-D3+1

count words in cell EX 06

Combining these steps gives us the formula:

=LEN(TRIM(B3))-LEN(SUBSTITUTE(B3," ",""))+1

count words in cell EX 01

Google Sheets –Count Total Words in a Cell

All of the above examples work exactly the same in Google Sheets as in Excel.

count-words-in-cell-Google-Function

Excel is a tool for storing, organizing, and visualizing a large volume of data. It uses a rectangular block known as a cell to store the data unit. This tool can be used to perform different tasks like creating graphs, and analyzing trends, to get insights from the data. Data analysis can be performed in many ways like visual analysis using graphs, mathematical or trend analysis using formulas, etc. It is primarily used for financial data analysis by accounting professionals but can be used by everyone as it is very easy to use and saves a lot of time. Let’s see how to count the number of words in a cell or range of cells.

Count the Number of Words in a Cell or a Range Cells in Excel

  1.  Firstly, we will remove any extra spaces present at the start or at the end of sentences or text data present inside the cell.
  2.  Calculate the total number of characters present including the spaces present in between the words.
  3.  Now, we will replace all the white spaces that are present in between words and then count the characters.
  4.  Calculate the difference between the total count of characters with spaces to that without spaces (step 2 – step 3). This will give the count of the total number of white spaces.
  5.  Add 1 to the difference to get the count of words.

For the purpose of demonstration, we will take one string- “Hello!, welcome to GeeksforGeeks.” and calculate the number of words present in it.

Step 1: Remove white spaces at the beginning or at the end of the string.

TRIM(): This function takes a cell with content and as a result return gives the same text without any white space at the beginning or end.

Input: ”          Hello, How are you?”

Output: Hello, How are you?

TRIM-function

Output

Output

Step 2: Count the number of characters with white spaces between the words.

LEN(): This function calculates the number of characters present in the cell.

LEN-function

Output

Output

Step 3: Replace the spaces with no space and then calculate the number of characters.

SUBSTITUTE(): This function replaces a piece of the text with another bit of text.

Syntax: SUBSTITUTE ( cell name, old_text, new_text)

SUBSTITUTE-function

Output

Output

We can see that the spaces are removed.

To count the characters we can add the LEN function with the substitute function line LEN(SUBSTITUTE(cell_name)).

LEN-SUBSTITUTE-function

Output

Output

Step 4: Calculating the difference 

Calculating-difference

Output

Output

Step 5: Add 1 to the difference value obtained

Adding-1-to-difference

Output

Output

The count of words in “Hello!, Welcome to GeeksforGeeks” is 4. Therefore, the formula to calculate the count of words in a cell is:

= LEN(TRIM(cell_name)) – LEN(SUBSTITUTE(A2, ” “, “”) + 1

Count words in the range of cells

Formula that can be used: =SUM(LEN(TRIM(cell_range))-LEN(SUBSTITUTE(cell_range,” “,””))+1)

Example: Suppose we have text in three cells and we want to calculate the total words present in those cells.

Dataset

Formula

Formula-used

Output

Output

I recently attended a workshop where panelists provided their best Excel tips. One tip involved filtering a range of cells containing a certain number of words. A nice tip, but it left attendees wondering how to count words in Excel. (Includes practice file.)

The summit tip was for a specific product, but opportunities exist where you might want to count words in an Excel cell. For example, I do a similar process when I pull a list of site search queries from my web analytics to see people’s interests.

Spaces Impact Word Count

The key to counting words in Excel is to correctly identify and count the spaces between and around the words. You need to remove leading and trailing spaces in the cells, or the word count will be inflated. There are a couple of ways to do this. A simple way is to use an Excel add-on such as ASAP Utilities.

Another way is to use the Excel TRIM function. The trim function removes leading and trailing spaces in a cell. In the screen snap below, you can see that the spaces aren’t always obvious. You have to compare the counts in Columns B and C

Excel sheet with examples of spaces in cells.

Excel sheet with leading and trailing spaces

In addition to the TRIM function, I’ll also use Excel’s LEN function and SUBSTITUTE functions. These are also considered TEXT functions.

LEN function returns the number of characters in a string. In my case, the number will reflect the number for each reference cell. Since a “space” is considered a character, it is counted.

SUBSTITUTE function is similar to “search and replace” on a cell, except we can specify how many times the substitution should occur. For example, you could indicate once, all, or a specific number. 

For example, the formula =SUBSTITUTE(A1,”firefox”,”google”) would replace the word “firefox” with “google” for cell reference A1.

For our purposes, we want to substitute a space “ “ with nothing “”. Effectively, the function removes all spaces, so the words run together. “Example text” would change to “Exampletext”. All the single spaces have been removed resulting in a string without spaces.

Understanding the Word Count Formula

One nice feature of Excel is that you can nest formulas that include multiple functions. The formula below references LEN, TRIM, and SUBSTITUTE. It also starts with the IF function, which we’ve outlined before.

To get the word count in cell A2 in my spreadsheet, I would use this formula in B2,

=IF(LEN(TRIM(A2))=0,0,LEN(TRIM(A2))-LEN(SUBSTITUTE(A2,” “,””))+1)

While stringing Excel functions together is efficient, it may make the formula intimidating. You’ll note in the screen snap below and on the lesson spreadsheet, I’ve added more columns to make this clearer.

Let me break this down for you.

  1. We TRIM any extra spaces in cell A2 and determine if the cell is blank by using =IF(LEN(TRIM(A2))=0,0. If A2 is blank, it assigns the word count as 0.
  2. If A2 isn’t blank, we count the characters in the cell using LEN(TRIM(A2)). You might think of this as our starting character count inclusive of spaces.
  3. We use LEN(SUBSTITUTE(A2)," ","") to remove the remaining spaces. We then count the characters in this new string.
  4. We take the LEN count from Step 2 and subtract the LEN count from Step 3. We then add 1 to the count to adjust for the first word.

In the above example, I placed the formula in Column B. However, you can also add more columns to show various stages. This often helps when learning a nested formula. In the screen snap below, my formula is in Column F.

Excel sheet with added column indicating word count

Final Word Counts in Column F

Presenting Another Way

If you prefer word problems, think of it this way. If the cell is empty, make the word count = 0. Otherwise, remove the extra spaces and count the characters in the cell. Hold that value as “A.” Now, remove all spaces in that cell and count the characters again. Hold that value as “B.” Your word count is (A-B) + 1.

“Sample example text” = LEN count of 19. This is your “A.”

“Sampleexampletext” = LEN count of 17. This is your “B.”

(19-17)+1 = word count of 3.

After writing this formula, I think I have a new appreciation for the ease at which some programs, like Microsoft Word, can return a word count.

Consider a Custom Function

After using this word count formula several times, I thought it would make more sense to create a custom function and assign it to the Excel workbook. This would save me from repeating these steps each time I needed to do an analysis.

You can use the code snippet below and add it as a module in the VB editor. In my example, I called the function CellWordCount. That name is one I’m apt to remember, but you can choose a different name for your custom function.

Function CellWordCount(rng As Range) As Integer
    CellWordCount = UBound(Split(Application.WorksheetFunction.Trim(rng.Value), " "), 1) + 1
End Function

To use the function, click in an empty cell and  type =CellWordCount and then your cell reference in parentheses.

Using the Custom Function

Feel free to download the practice file and play around with it. Try editing some of the examples to include things like typos with consecutive extra space characters in between words. The sample workbook contains the formulas referenced here except for the custom function. Also, Microsoft has a page on how to create custom functions.

Now that we have had Excel count words, we can filter that column for a minimum or maximum value. Another option might be to convert the spreadsheet into a table and then add an Excel slicer.

Downloadable Resource

Hand-picked Excel Tutorials

  • How to Sort Excel by Color

Excel has built-in functions to count cells based on various condition(s). These include cells containing specific values like numbers, text, blank or non-blank values, and to calculate the length of a string. But unfortunately, there is no special built-in function to count words in Excel. This is possible, however, with the right formula.

How to count words in Excel

To count words in Excel, you need to use a special formula by combining various functions. Using a special formula you can easily count total words in a cell or range, and you can also count the number of times a word appears in a cell or range of cells. The formula for words count in a cell and range has some variations, such as;

  • If you need to count total words in a cell or number of times a word appears in a cell, then the formula would be a combination of LEN, TRIM and SUBSTITUTE functions.
  • But if you need to count total words in a range or the number of times a word appears in a range, then the formula would be a combination of SUMPRODUCT or SUM, LEN, TRIM and SUBSTITUTE functions.

In this article, you will learn how to count words in Excel. Excel word count could be in a cell or range, and you will also learn to count specific words in Excel appeared in a cell or range.

How to count total words in a cell

As explained above, to count total words in a cell you need to formulate a formula by combining LEN, TRIM and SUBSTITUTE functions as per the following syntax;

=LEN(TRIM(cell_ reference))-LEN(SUBSTITUTE(cell_ reference," ",""))+1

For example, to count words in cell A1, the formula would be;

=LEN(TRIM(A1))-LEN(SUBSTITUTE(A1," ",""))+1

You need to copy down this formula to other rows that have text strings.

How this formula works

The TRIM function eliminates extra spaces at the start and end of a text string, and the LEN function calculates the total length of a string in cell A1 LEN(TRIM(A1)). It gives you the Total length of the string.

In the second step, SUBSTITUTE function replaces all the spaces with an empty text string (“”), and LEN function calculates the length of resulting string in cell A1LEN(SUBSTITUTE(A1,” “,””)). Final you add 1 to the final word count.

In simple words, this formula will calculate the word count in the following way;

=Total length of string – string length without spaces +1

= total words in a cell

For example, you have text strings in multiple cells, and you need to count total words in each cell. You need to apply this formula in the first cell and copy it down to other cells in rows to come up with the total word count, such as;

=LEN(TRIM(A2))-LEN(SUBSTITUTE(A2," ",""))+1

How to count specific words in a cell

If you need to count how many times a specific word appears in a cell, then you need to use the following formula as a combination of LEN, TRIM and SUBSTITUTE functions.

=(LEN(TRIM(cell_ref))-LEN(SUBSTITUTE(cell_ref,word,"")))/LEN(word)

You can enter the specific word directly in this formula or you can use cell reference where that word is stored and copy down the formula to other rows.

For example, you have a text string in cell A2 and a specific word stored in cell B1 then the formula would be;

=(LEN(TRIM(A2))-LEN(SUBSTITUTE(A2,$B$1,"")))/LEN($B$1)

Note: This formula is case-sensitive as SUBSTITUTE function is case-sensitive in Excel, so you need to be careful while entering specific words for the count in this formula.

How this formula works

In the first part, LEN and TRIM functions calculate the total length of the string in cell A2 “LEN(TRIM(A2))” after eliminating extra spaces at the start and end of the string to come up with the total length of the string.

In the second part, LEN and SUBSTITUTE functions calculate the length of the string after replacing the specific word with an empty text string “LEN(SUBSTITUTE(A2,” “,””))”.

Finally, you subtract the second part from the first part and divide the resulting figure by length of specific word string.  

In simple words, this formula will calculate the words count in the following way;

=(Total length of string – string length without a specific word)/Length of specific word

= Total specific words in a cell

For example, you want to count how many times a word “Excel” appears in each cell, and you will use the following formula for this purpose;

=(LEN(TRIM(A2))-LEN(SUBSTITUTE(A2,"Excel","")))/LEN("Excel")

How to count total words in a range

If you want to calculate total words in a range, then you need to use a formula as the combination of SUMPRODUCT or SUM, LEN, TRIM and SUBSTITUTE functions as per the following syntax;

=SUMPRODUCT(LEN(TRIM(range))-LEN(SUBSTITUTE(range," ",""))+1)

OR

=SUM(LEN(TRIM(range))-LEN(SUBSTITUTE(range," ",""))+1)

As you can see, this formula is same as of total words count in a cell, but it has additional SUMPRODUCT or SUM function to sum the resulting array of the word count in all the cells of a range.

The SUMPRODUCT function by default sums an array, so you need to enter it as usual by just pressing Enter key. But for the SUM function to sum an array, you need to convert the formula into an array formula by pressing Ctrl+Shift+Enter keys.

The formula to count total words in a range would be;

=SUMPRODUCT(LEN(TRIM(A2:A4))-LEN(SUBSTITUTE(A2:A4," ",""))+1)

How to count specific words in a range

When you need to count how many times a specific word appears in a range of cells then you need to use formula as per the following syntax;

=SUMPRODUCT((LEN(TRIM(range))-LEN(SUBSTITUTE(range,word,"")))/LEN(word))

Here, you only need to wrap the formula of specific word count in a cell into SUMPRODUCT or SUM function to sum the resulting array of specific word count in all the cells of range.

If you need to use SUMPRODUCT function, then use it as usual by pressing Enter key as it by default sums array. But if you use the SUM function to sum arrays, then you need to convert formula into an array by pressing Ctrl+Shift+Enter keys.

Here is the formula to count the specific word “Excel” in a range;

=SUMPRODUCT((LEN(TRIM(A2:A4))-LEN(SUBSTITUTE(A2:A4,"Excel","")))/LEN("Excel"))

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. 

Понравилась статья? Поделить с друзьями:
  • Excel count the number of
  • Excel count rows in cell no
  • Excel deter для собак побочные эффекты
  • Excel count of values in cell
  • Excel deter 8in1 отзывы