試試這個:
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
時,「德州的大學」的所有部分字符串中被發現,你需要調整一下代碼,返回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
注意,這最後片斷沒有經過測試和順序的話都在字符串中發現的不關心。
是。現在你有沒有具體的編程問題? –
我正在使用excel-vba進行編程。我試圖在excel-vba中的sql查詢中實現類似的運算符功能。我不知道它爲什麼減1。 – Ramesh