3

我正在使用 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吗?

4

2 回答 2

16

Like运算符已在 VBA 中可用:

If "I am studying at University of Texas at Arlington" Like "*Univ*of*Texas*" Then
    MsgBox "Yes, it is!"
End If
于 2013-07-27T14:47:40.160 回答
6

试试这个:

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

请注意,最后一个片段没有经过测试,也不关心单词在字符串中的顺序。

于 2013-07-27T01:36:06.937 回答