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
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.

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
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,164,313
Messages
5,836,589
Members
430,438
Latest member
David Gr

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