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

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
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.
 
Upvote 0
nicolewh,


Try:


Code:
Sub countwordsincell()

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

End Sub
 
Upvote 0
Shorter ;)

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

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

Forum statistics

Threads
1,213,561
Messages
6,114,317
Members
448,564
Latest member
ED38

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
Back
Top