Excel VBA就像运算符一样

时间:2013-07-27 01:10:49

标签: string vba excel-vba excel

我正在使用excel VBA在另一个字符串中搜索子字符串,如下所示。

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

如果pos返回非负值,则表示我在字符串中有子字符串。 但是,我需要更复杂的搜索,子字符串可以是“Univ of Tex”

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

不起作用。

根据最大搜索条件,我需要说子串存在。是否可以使用excel VBA?

2 个答案:

答案 0 :(得分:16)

Like运算符已在VBA中可用:

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

答案 1 :(得分:5)

试试这个:

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()指定所需数量的值,并在找到的第一个匹配项中退出该函数。

如果您特别想在字符串中找到“Univ of Tex”的所有部分时返回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

请注意,最后一个代码段未经过测试,并不关心字符串中单词的顺序。