Hello, this has got to be one of my most tresured pieces of code, so I thought it can't be that bad, so I decided to share it in the code bank!
vb Code:
Module Module1
Public Function MyWordCount(ByVal TextToBeCounted As String) As Integer
Dim SpacePos As Integer ' Stores the value returned from Instring where a space char is found.
Dim X As Integer ' X tells InString from which char position to start from.
Dim WordCount As Integer ' How many words there are.
Dim NoMore As Boolean ' Yes or No.
Dim CharValue As Integer
WordCount = 0
X = 1
NoMore = False
TextToBeCounted = TextToBeCounted.Replace(vbCr, " ")
TextToBeCounted = TextToBeCounted.Replace(vbLf, " ")
If TextToBeCounted.Trim.Length > 0 Then
Do While NoMore = False
SpacePos = InStr(X, Trim(TextToBeCounted), " ")
If SpacePos > 0 Then
CharValue = Asc(TextToBeCounted.Substring(X - 1, 1))
If CharValue > 64 AndAlso CharValue < 91 OrElse CharValue > 96 AndAlso CharValue < 123 OrElse CharValue > 47 AndAlso CharValue < 58 Then
WordCount += 1
End If
X = SpacePos + 1
Do While InStr(X, (TextToBeCounted.Substring(X - 1, 1)), " ") > 0
X += 1
Loop
Else
If X <= TextToBeCounted.Length Then
CharValue = Asc(TextToBeCounted.Substring(X - 1, 1))
If CharValue > 64 AndAlso CharValue < 91 OrElse CharValue > 96 AndAlso CharValue < 123 OrElse CharValue > 47 AndAlso CharValue < 58 Then
WordCount += 1
End If
End If
NoMore = True
End If
Loop
End If
MyWordCount = WordCount
End Function
End Module
This code is losely coupled so all you have to do is call into this function from say, the click of a button.
I would also like to mention MrLudwig for helping me with this code!