Comment calculer le nombre de mots dans une cellule Excel ?

Count Words in Excel: Your Ultimate Guide

02/07/2010

Rating: 4.97 (9745 votes)

Microsoft Excel is an indispensable tool for organising, analysing, and managing vast amounts of data. While often associated with numerical calculations, Excel is equally powerful when handling text-based information. There are many scenarios where you might need to determine the word count within a cell or a range of cells, such as adhering to character limits, performing content analysis, or simply understanding the density of your textual data. Manually counting words can be tedious and prone to error, especially with large datasets. Fortunately, Excel offers several efficient methods, from built-in formulas to custom VBA functions, to automate this task with precision.

Comment compter les mots dans une cellule ?
Apporte des onglets efficaces à Office (y compris Excel), tout comme Chrome, Edge et Firefox. Utilisez des formules Excel pour compter les mots dans une cellule, offrant une analyse rapide du nombre de mots pour le contenu ou les entrées de données.

This comprehensive guide will walk you through the various techniques to accurately count words in Excel, ensuring you can tackle any text-counting challenge. We'll explore the core formulas, discuss how to handle tricky extra spaces, and even delve into more advanced methods like VBA for greater flexibility and automation. By the end of this article, you'll be able to count words in your spreadsheets like a true Excel expert.

Table

Counting Words Using Excel's Built-in Formulas

The most common and straightforward way to count words in Excel is by leveraging a combination of its powerful built-in functions. The fundamental principle revolves around counting the number of spaces in a given text string, as the number of words is typically one more than the number of spaces separating them. However, this method requires careful handling of superfluous spaces that can skew your results.

The Basic Word Count Formula

Let's start with a foundational formula. This formula works well for text where each word is separated by a single space, and there are no leading or trailing spaces.

The logic is simple: determine the total length of the text, then subtract the length of the text after all spaces have been removed. The difference gives you the number of spaces. Add one to this number to get the total word count.

Suppose your text is in cell A1. You would use the following formula:

=LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1
  • LEN(A1): Calculates the total number of characters in cell A1, including spaces.
  • SUBSTITUTE(A1," ",""): Replaces every instance of a space (" ") in cell A1 with an empty string (""). Essentially, it removes all spaces.
  • LEN(SUBSTITUTE(A1," ","")): Calculates the length of the text after all spaces have been removed.
  • Subtracting the two LEN results gives you the number of spaces.
  • Adding +1 accounts for the fact that the number of words is one more than the number of spaces separating them.

Example: If cell A1 contains "This is an example text.", then:

  • LEN("This is an example text.") is 25.
  • SUBSTITUTE("This is an example text."," ","") results in "Thisisanexampletext.".
  • LEN("Thisisanexampletext.") is 21.
  • 25 - 21 = 4 (number of spaces).
  • 4 + 1 = 5 (number of words).

Handling Superfluous Spaces with TRIM

The basic formula is effective, but real-world data often isn't perfectly clean. You might encounter text with leading or trailing spaces, or multiple spaces between words. These extra spaces will be counted as distinct "words" by the basic formula, leading to an inaccurate count. This is where the TRIM function becomes invaluable.

The TRIM function removes all spaces from text except for single spaces between words. It cleans up leading, trailing, and multiple internal spaces, ensuring your word count is accurate.

The robust formula that accounts for extra spaces is:

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

Let's break down how this improved formula works:

  • TRIM(A1): First, this function cleans the text in A1 by removing any leading or trailing spaces and reducing multiple spaces between words to a single space.
  • LEN(TRIM(A1)): Calculates the length of the cleaned text.
  • SUBSTITUTE(TRIM(A1)," ",""): Removes all spaces from the *cleaned* text.
  • LEN(SUBSTITUTE(TRIM(A1)," ","")): Calculates the length of the cleaned text without any spaces.
  • The rest of the formula (subtraction and +1) works the same way as the basic formula, but now operates on a clean string, guaranteeing an accurate word count.

Example: If cell A1 contains " Here is some text. "

  • TRIM(" Here is some text. ") results in "Here is some text.".
  • LEN("Here is some text.") is 20.
  • SUBSTITUTE("Here is some text."," ","") results in "Hereissometext.".
  • LEN("Hereissometext.") is 17.
  • 20 - 17 = 3 (number of spaces).
  • 3 + 1 = 4 (number of words).

This robust formula is generally the preferred method for counting words in a single Excel cell.

Counting Words Across a Range of Cells

If you need to count the total number of words across multiple cells, you can adapt the robust formula using an array formula with the SUM function.

Suppose you want to count words in cells A2 to A4. The formula would be:

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

Important Note: This is an array formula. After typing it into the cell, you must press Ctrl + Shift + Enter simultaneously. Excel will automatically add curly braces {} around the formula, indicating it's an array formula. If you just press Enter, you will likely get an error or an incorrect result.

This array formula processes each cell in the specified range (A2:A4) individually, calculates its word count, and then sums all those individual counts to give you a grand total for the entire range.

Comparing Basic vs. Robust Formulas

To illustrate the importance of using TRIM, consider the following table:

Text in Cell A1Basic Formula ResultRobust Formula Result (with TRIM)Actual Word Count
"Hello world"222
" Leading spaces"322
"Multiple spaces"422
"Trailing spaces "322
" Mixed spaces here "644

As the table clearly shows, the robust formula using TRIM consistently provides the accurate word count, making it the preferred method for reliable data analysis.

Counting Words Using VBA (Visual Basic for Applications)

For more complex scenarios, or if you frequently need to perform word counts and want to create a reusable custom function, VBA (Visual Basic for Applications) offers powerful solutions. You can create either a User-Defined Function (UDF) that behaves like a standard Excel function or a Subroutine (macro) to run a specific word-counting task.

Creating a User-Defined Function (UDF) for Word Count

A UDF allows you to create your own custom function that you can then use directly in your spreadsheet formulas, just like SUM or LEN.

Follow these steps:

  1. Press Alt + F11 to open the Microsoft Visual Basic for Applications window.
  2. In the VBA editor, click on Insert > Module.
  3. A new module window will open. Paste the following VBA code into it:
Function CountWords(rng As Range) As Long Dim cell As Range Dim totalWords As Long Dim textValue As String totalWords = 0 For Each cell In rng ' Trim the cell value to handle extra spaces textValue = Trim(cell.Value) ' Check if the cell is not empty after trimming If Len(textValue) > 0 Then ' Split the string by spaces and count the elements ' UBound returns the upper bound of the array (0-indexed), so add 1 for total elements totalWords = totalWords + UBound(Split(textValue, " "), 1) + 1 End If Next cell CountWords = totalWords End Function
  1. Close the VBA editor (Alt + Q or click the X).

Now, you can use this custom function in your Excel worksheet:

  • To count words in a single cell (e.g., A1): =CountWords(A1)
  • To count words in a range of cells (e.g., A2:A10): =CountWords(A2:A10)

This UDF is robust as it iterates through each cell in the specified range and uses the Trim function and Split function (which creates an array from the text based on a delimiter, in this case, a space) to accurately count words, even with messy data.

Comment compter les mots dans Excel ?
Compter les Mots : – Supposons que vous souhaitez compter les mots dans la cellule A1. – Dans une cellule vide, entrez la formule suivante pour compter les mots dans A1 : `=NB.MOTS (A1)`. – Excel comptera automatiquement le nombre de mots dans la cellule A1 et affichera le résultat dans la cellule où vous avez entré la formule.

Creating a VBA Subroutine (Macro) for Word Count

A subroutine is a macro that performs a specific task. You might use this if you want to get a total word count for a selected area or an entire sheet and display it in a message box, rather than in a cell.

Follow these steps:

  1. Press Alt + F11 to open the Microsoft Visual Basic for Applications window.
  2. In the VBA editor, click on Insert > Module.
  3. Paste the following VBA code into it:
Sub CountWordsInSelection() Dim Rng As Range Dim totalWords As Long Dim cellText As String totalWords = 0 ' Check if a range is selected, otherwise use the UsedRange of the active sheet If Not Selection Is Nothing And TypeName(Selection) = "Range" Then Set Rng = Selection Else Set Rng = ActiveSheet.UsedRange End If For Each cell In Rng cellText = Trim(cell.Value) If Len(cellText) > 0 Then ' Split the trimmed text by spaces and count the elements totalWords = totalWords + UBound(Split(cellText, " "), 1) + 1 End If Next cell MsgBox "Total words in selected range: " & Format(totalWords, "#,##0"), vbInformation, "Word Count Report" End Sub
  1. Close the VBA editor.

To run this macro:

  1. Select the cells you want to count (or select nothing to count the entire used range of the active sheet).
  2. Press Alt + F8 to open the Macro dialogue box.
  3. Select CountWordsInSelection from the list and click Run.
  4. A message box will appear displaying the total word count.

Counting Specific Words in Excel

Beyond counting all words, you might need to count the occurrences of a particular word or phrase within your data. This is useful for keyword analysis, content auditing, or tracking specific terms.

Counting a Specific Word in a Single Cell (Case-Sensitive)

To count how many times a specific word appears in a cell, you can use a formula that compares the length of the original text with the length of the text after removing all instances of the specific word. The difference in length, divided by the length of the specific word itself, gives you the count.

Suppose you want to count the word "Excel" in cell A2:

=(LEN(A2)-LEN(SUBSTITUTE(A2,"Excel"," ")))/LEN("Excel")
  • SUBSTITUTE(A2,"Excel"," "): Replaces every occurrence of "Excel" with an empty string.
  • LEN(A2)-LEN(SUBSTITUTE(A2,"Excel"," ")): Calculates the total number of characters that were removed (which is the total length of all "Excel" instances).
  • LEN("Excel"): The length of the word "Excel" (which is 5).
  • Dividing the difference by the word's length gives you the count of its occurrences.

Note: This formula is case-sensitive. "Excel" will be counted, but "excel" or "EXCEL" will not.

Counting a Specific Word in a Single Cell (Case-Insensitive)

To make the specific word count formula case-insensitive, you can convert both the cell's content and the word you're searching for to either uppercase or lowercase using the UPPER or LOWER functions before performing the substitution.

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

Here, UPPER(A2) converts the text in cell A2 to uppercase, and UPPER("Excel") converts "Excel" to uppercase. This ensures that "Excel", "excel", and "EXCEL" are all treated as the same for counting purposes.

Counting a Specific Word Across a Range of Cells

To count the occurrences of a specific word across a range of cells, you can combine the case-insensitive formula with the SUM function as an array formula.

For example, to count "Excel" (case-insensitive) in cells A2 to A3:

=SUM((LEN(A2:A3)-LEN(SUBSTITUTE(UPPER(A2:A3),UPPER("Excel"),"")))/LEN("Excel"))

Remember, this is an array formula, so you must press Ctrl + Shift + Enter after entering it.

Frequently Asked Questions (FAQs)

Q1: Does the word count formula count numbers or punctuation?

A: The standard word counting formulas (using LEN, TRIM, and SUBSTITUTE) primarily count sequences of characters separated by spaces. If numbers or punctuation marks are part of a sequence separated by spaces, they will be considered part of a "word". For example, "123 Main St." would typically be counted as 3 words ("123", "Main", "St."). If you need to exclude numbers or specific punctuation, you would need more advanced formulas using CLEAN, SUBSTITUTE multiple times for different characters, or custom VBA to strip them out before counting.

Q2: How do I count words in multiple sheets?

A: The built-in Excel formulas are designed to work within a single sheet or a defined range on that sheet. To count words across multiple sheets, your best option is to use a VBA User-Defined Function (UDF) or a macro. The CountWords UDF provided earlier can be adapted to take a range spanning multiple sheets (e.g., =CountWords(Sheet1!A1:A10, Sheet2!A1:A10), though this requires modifying the UDF to accept multiple range arguments or summing the UDF calls for each sheet). A macro is often simpler for a one-off report, iterating through all sheets in the workbook.

Q3: What if a cell contains an error or is completely empty?

A: Our robust word count formula =LEN(TRIM(A1))-LEN(SUBSTITUTE(TRIM(A1)," ",""))+1 will return 1 for an empty cell, which is often not desired. To handle empty cells, you can wrap the formula in an IF statement:

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

This formula checks if the trimmed cell is empty; if so, it returns 0, otherwise, it performs the word count. For cells containing errors (e.g., #N/A), the formula will also return an error. You can further wrap it in IFERROR to handle this gracefully: =IFERROR(IF(TRIM(A1)="",0,LEN(TRIM(A1))-LEN(SUBSTITUTE(TRIM(A1)," ",""))+1),0)

Q4: Can I count words that are part of a larger string but not separated by spaces?

A: The standard word count methods rely on spaces as delimiters. If you have "word1word2" and want to count "word1" and "word2" separately, the formulas won't do that automatically. You would need more complex text parsing techniques, potentially involving regular expressions (which Excel's native formulas don't support directly, but VBA can) or a series of FIND and MID functions to extract and count specific patterns.

Q5: Is there a built-in "word count" feature in Excel like in Word?

A: No, unlike Microsoft Word, Excel does not have a direct "word count" feature accessible from the ribbon or status bar that provides a total count for selected cells. This is why using formulas or VBA is necessary for this task.

Conclusion

Counting words in Excel might not be as intuitive as in a word processor, but with the right formulas and techniques, it's a straightforward process. Whether you need a quick count for a single cell, a total for a large range, or specific keyword analysis, Excel provides the tools to get the job done efficiently. The robust formula using LEN(TRIM(...))-LEN(SUBSTITUTE(...))+1 is your go-to for general word counting, ensuring accuracy by handling those pesky extra spaces. For advanced customisation or repetitive tasks across multiple sheets, delving into VBA offers unparalleled flexibility.

By mastering these methods, you'll enhance your data analysis capabilities and ensure the integrity of your textual information within spreadsheets. Keep these formulas and VBA snippets handy, and you'll always be prepared to accurately count every word in your Excel documents.

If you want to read more articles similar to Count Words in Excel: Your Ultimate Guide, you can visit the Automotive category.

Go up