Home » excel » excel – VBA Word count in range

excel – VBA Word count in range

Posted by: admin May 14, 2020 Leave a comment


Hi I am a beginner in excel so please bear with my ignorance.
Lately i found myself in need of a function that counts the number of words in a range of cells (counting the empty cells as 0, of course).
Surfing the net i found this simple VBA code:

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

I found this extremly useful as i could just use


in excel function bar to sum the number of words contained in 3 cells without counting the empty ones.

The problem is that i now need to do this on a large range of cells in a column and simply using


does not work.
I think the error is that it tries to apply the function on the range considering it as a single big cell whereas i want it to apply the function to every single cell in the range and sum every output to obtain the total.
I’d be really grateful if someone could help me cause i can’t figure out a solution.
I’m using Excel 2016.
Thank you very much for your assistance.

How to&Answers:

Loop through the cells and apply the same logic.

The function will now work for single-cell ranges & multi-cell ranges

Function intWordCount(rng As Range) As Integer

Dim MyCell as Range

For Each MyCell in rng
    intWordCount = intWordCount + UBound(Split(Application.WorksheetFunction.Trim(MyCell.Value), " "), 1) + 1
Next MyCell

End Function


If you have a recent version of Excel:

Function intWordCount(rng As Range) As Long
    Dim wf As WorksheetFunction, s As String
    Set wf = Application.WorksheetFunction

    s = wf.TextJoin(" ", True, rng)
    intWordCount = UBound(Split(wf.Trim(s), " "), 1) + 1
End Function