返回一个单元格中有多less个单词

任何人都可以帮助我一个关于如何返回与VBA单元的单词数量的意见?

在Excel中,我使用C2=LEN(B2)-LEN(SUBSTITUTE(B2," ",""))+1 ,但在VBA中看起来” SUBSTITUTE “函数不再起作用。

拆分空间字符并获得结果数组的上边界。

 dim numchars as long numchars = ubound(split(range("b2").value2, chr(32)))+1 debug.print numchars 

1被添加,因为VBA数组的默认开始(lbound)为零。

顺便说一句,工作表SUBSTITUTEfunction的VBA相当于replace。

一个正则Regexp选项可确保只返回有效的单词,并忽略任何引导的空白问题。

 Function NumWords(strIn As String) As Long Dim objRegex As Object Dim objRegMC As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = "\b[az]+\b" .Global = True If .test(LCase$(strIn)) Then Set objRegMC = .Execute(strIn) NumWords = objRegMC.Count Else NumWords = 0 End If End With End Function