2013-07-27 60 views
1

我正在使用excel VBA搜索另一個字符串中的子字符串,如下所示。Excel VBA像運算符

Dim pos As Integer 
pos = InStr("I am studying at University of Texas at Arlington", "University of Texas") 

如果pos返回一個非負值,這意味着我必須在字符串中的子字符串。 然而,我需要一個更復雜的搜索,其中子可以是「德州的大學」

InStr("I am studying at University of Texas at Arlington", "Univ of Tex") 

不適合這項工作。

根據最大搜索詞,我需要說子串是存在的。是否有可能使用Excel VBA?

+0

是。現在你有沒有具體的編程問題? –

+1

我正在使用excel-vba進行編程。我試圖在excel-vba中的sql查詢中實現類似的運算符功能。我不知道它爲什麼減1。 – Ramesh

回答

11

Like運營商已經可以在VBA:

If "I am studying at University of Texas at Arlington" Like "*Univ*of*Texas*" Then 
    MsgBox "Yes, it is!" 
End If 
+0

好的,趕上!在這種情況下,這正是要做的事情。然而'Like'往往被誤用於其他功能,如我建議的功能,這就是爲什麼我傾向於避免它,我想我已經看到它被濫用了很多次...(+1) –

+0

是,它肯定會被濫用。通常(使用數據庫表)人們嘗試創建過於廣泛的搜索功能時,他們應該首先使用其他字段上的條件減少搜索行數。 –

4

試試這個:

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 

注意,這最後片斷沒有經過測試和順序的話都在字符串中發現的不關心。