试试这个:
Public Function StringContainsAny(string_source As String, _
ByVal caseSensitive As Boolean, _
ParamArray find_values()) As Boolean
Dim i As Integer, found As Boolean
If caseSensitive Then
For i = LBound(find_values) To UBound(find_values)
found = (InStr(1, string_source, _
find_values(i), vbBinaryCompare) <> 0)
If found Then Exit For
Next
Else
For i = LBound(find_values) To UBound(find_values)
found = (InStr(1, LCase$(string_source), _
LCase$(find_values(i)), vbBinaryCompare) <> 0)
If found Then Exit For
Next
End If
StringContainsAny = found
End Function
用法:
Dim SomeString As String
SomeString = "I am studying at University of Texas at Arlington"
Debug.Print StringContainsAny(SomeString, False, "university of texas") 'True
Debug.Print StringContainsAny(SomeString, True, "university of texas") 'False
Debug.Print StringContainsAny(SomeString, True, "University of Texas") 'True
但是也:
Debug.Print StringContainsAny(SomeString, False, "TEXAS", "SMURF") 'True
和:
Debug.Print StringContainsAny(SomeString, False, "univ", "of", "tex") 'True
或者:
Dim Words As String()
Words = Split("univ of tex", " ")
Debug.Print StringContainsAny(SomeString, False, Words) 'True
您可以为 指定任意数量的值find_values()
,并且该函数在找到的第一个匹配项时退出。
如果您特别想true
在字符串中找到“Univ of Tex”的所有部分时返回,则必须稍微调整代码,以便true
在字符串中找到所有传递的参数时返回。但是也许应该重命名该方法StringContainsAll
- 可能是这样的:
Public Function StringContainsAll(string_source As String, _
ByVal caseSensitive As Boolean, _
ParamArray find_values()) As Boolean
Dim i As Integer, found As Boolean
If caseSensitive Then
For i = LBound(find_values) To UBound(find_values)
found = (InStr(1, string_source, find_values(i), vbBinaryCompare) <> 0)
If Not found Then Exit For
Next
Else
For i = LBound(find_values) To UBound(find_values)
found = (InStr(1, LCase$(string_source), _
LCase$(find_values(i)), vbBinaryCompare) <> 0)
If Not found Then Exit For
Next
End If
StringContainsAll = found
End Function
请注意,最后一个片段没有经过测试,也不关心单词在字符串中的顺序。