A Visual Basic function that counts the number of words in a sentence or text file can become quickly very complex, and usually doesn’t execute fast enough for most purposes. Thanks to the RegEx object that comes with the Microsoft VBScript Regular Expression type library, this task becomes trivial. Here’s all the code that you need:
' Count the number of words in the string argument'' NOTE: requires a reference to the ' Microsoft VBScript Regular Expression type libraryFunction CountWords(ByVal Text As String) As Long Dim re As New RegExp ' the following pattern means that we're looking for a word character (w) ' repeated one or more times (the + suffix), and that occurs on a word ' boundary (leading and trailing sequences) re.Pattern = "w+" ' search for *all* occurrences re.Global = True ' the Execute method does the search and returns a MatchCollection object ' which in turn exposes the Count property, ' i.e. the result we're interested into CountWords = re.Execute(Text).CountEnd Function