如何检查字符串中某个范围的出现?
How to check for occurences of a range in a string?
所以我有几个单词的垂直范围,我在一个单元格中有一个字符串形式的句子。我想知道如何编写一些代码来检查字符串中单词范围的出现次数。不一定是连续的。因此,例如,a1:a3 可能是单词 apple pear orange,字符串可能是“I love pear and apple!”该函数将输出 2。我在这里写下了一些代码,但它仅在使用字符串而不是范围进行搜索时有效。
Function WordListCount(TextString As String, rng As String) As Integer
TextString = LCase(TextString)
Dim Result() As String
Dim Result2() As String
Dim Count As Integer
Result = Split(TextString, " ")
Result2 = Split(rng, " ")
Count = UBound(Result())
Dim k As Integer
Dim i As Integer
Dim repeat As Integer
repeat = 0
For i = LBound(Result) To UBound(Result)
For k = LBound(Result2) To UBound(Result2)
If StrComp(Result(i), Result2(k)) = 0 Then
repeat = repeat + 1
End If
Next k
Next i
WordListCount = repeat
End Function
由于如果您要搜索的是字符串而不是范围,此代码可以正常工作,那么我如何才能将范围转换为字符串?最好用 space?
分隔
在一般句子结构中拆分单词时,您可能不仅希望根据空格拆分,还希望根据标点符号拆分。一种简单的方法是使用正则表达式,因此添加对库的引用:
工具 -> 参考 -> Microsoft VBScript 正则表达式 #
从那里,您可以将文本字符串拆分为单词并将它们与您的范围进行匹配:
Function WordListCount(TextString As String, rng As Range) As Integer
Dim Rex, Matches, Count
WordListCount = 0
Set Rex = New RegExp
Rex.Pattern = "\w+"
Rex.Global = True
Set Matches = Rex.Execute(TextString)
For Each Match In Matches
For Each Cell In rng
If (StrComp(Match.Value, Cell.Value, vbTextCompare) = 0) Then
WordListCount = WordListCount + 1 ' Found word
Exit For
End If
Next
Next
End Function
可以直接引用范围,不需要转成字符串:
Debug.Print WordListCount("I love pear and apple!", Range("A1:A3"))
所以我有几个单词的垂直范围,我在一个单元格中有一个字符串形式的句子。我想知道如何编写一些代码来检查字符串中单词范围的出现次数。不一定是连续的。因此,例如,a1:a3 可能是单词 apple pear orange,字符串可能是“I love pear and apple!”该函数将输出 2。我在这里写下了一些代码,但它仅在使用字符串而不是范围进行搜索时有效。
Function WordListCount(TextString As String, rng As String) As Integer
TextString = LCase(TextString)
Dim Result() As String
Dim Result2() As String
Dim Count As Integer
Result = Split(TextString, " ")
Result2 = Split(rng, " ")
Count = UBound(Result())
Dim k As Integer
Dim i As Integer
Dim repeat As Integer
repeat = 0
For i = LBound(Result) To UBound(Result)
For k = LBound(Result2) To UBound(Result2)
If StrComp(Result(i), Result2(k)) = 0 Then
repeat = repeat + 1
End If
Next k
Next i
WordListCount = repeat
End Function
由于如果您要搜索的是字符串而不是范围,此代码可以正常工作,那么我如何才能将范围转换为字符串?最好用 space?
分隔在一般句子结构中拆分单词时,您可能不仅希望根据空格拆分,还希望根据标点符号拆分。一种简单的方法是使用正则表达式,因此添加对库的引用:
工具 -> 参考 -> Microsoft VBScript 正则表达式 #
从那里,您可以将文本字符串拆分为单词并将它们与您的范围进行匹配:
Function WordListCount(TextString As String, rng As Range) As Integer
Dim Rex, Matches, Count
WordListCount = 0
Set Rex = New RegExp
Rex.Pattern = "\w+"
Rex.Global = True
Set Matches = Rex.Execute(TextString)
For Each Match In Matches
For Each Cell In rng
If (StrComp(Match.Value, Cell.Value, vbTextCompare) = 0) Then
WordListCount = WordListCount + 1 ' Found word
Exit For
End If
Next
Next
End Function
可以直接引用范围,不需要转成字符串:
Debug.Print WordListCount("I love pear and apple!", Range("A1:A3"))