Macro to count number of words in cell A1

nicolewh

Well-known Member
Joined
Aug 7, 2009
Messages
554
I need a macro to count the number of words in cell A1 sheet1.

Failed example:
Code:
sub countwordsincell()
msgbox countwords(range("a1"))
end sub
Words in cell a1 = "Only if we had a macro to count words"
results:
msgbox says 9
Thanks!


Nicole
 

Some videos you may like

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.

Blade Hunter

Well-known Member
Joined
Mar 13, 2008
Messages
3,147
Code:
msgbox len(Range("A1").Text)-len(replace(Range("A1").text," ",""))+1

It works by taking the length of the string, it then takes away the length of the string minus spaces (pretty much counts the spaces) then it adds one because you don't have a space at the end of the last word. This will fail if there are any double spaces in the string.
 

hiker95

Well-known Member
Joined
Apr 8, 2009
Messages
17,649
nicolewh,


Try:


Code:
Sub countwordsincell()

MsgBox "Cell A1 contains : " & Len(Trim([A1])) - Len(Application.Substitute(Trim([A1]), " ", "")) + 1 & " words."

End Sub
 

Blade Hunter

Well-known Member
Joined
Mar 13, 2008
Messages
3,147
Shorter ;)

Code:
msgbox ubound(split(Range("A1").Text," "))+1

Count the upper boundary of an array split on the space +1
 

Watch MrExcel Video

Forum statistics

Threads
1,122,521
Messages
5,596,644
Members
414,083
Latest member
Mrsash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top