如何在没有空格的字符串中识别子字符串

时间:2018-02-27 10:55:19

标签: excel-vba vba excel

我希望检查字符串PROD中是否存在子字符串Today's proDuction,并将值返回为True或False。

这里的预期答案是正确的。

如何在VBA中执行此操作

2 个答案:

答案 0 :(得分:3)

使用Like

Sub testString()

    Dim myStr As String

    myStr = "Today's production"

    MsgBox myStr Like "*prod*"

End Sub
  

如果你想要不区分大小写的结果,这需要在你的模块顶部使用Option Compare Text ,因为默认的比较方法是比较二进制( case敏感的)。

如果您不想检查区分大小写,则Jeeped建议的更简单的方法最好。

Sub testString()

    Dim myStr As String

    myStr = "Today's proDuction"

    MsgBox InStr(1, myStr, "prod", vbTextCompare) > 0

End Sub

答案 1 :(得分:2)

我原来的回答:

Instr(Ucase("Today's proDuction"), "PROD") > 0

Instr(Lcase("Today's proDuction"), "prod") > 0

编辑: 根据下面@ GSerg的评论和@KDavis的回答,我认为值得研究和比较不同的方法。有趣的是,结果并不像我预期的那样。这是我的测试代码:

Option Explicit
Option Compare Text

Sub A()

    Dim i As Long
    Dim res As Boolean

    '// Timer class courtesy of @Mike Woodhouse here:
    '// https://stackoverflow.com/questions/198409/how-do-you-test-running-time-of-vba-code
    Dim tt As cTimer

    Set tt = New cTimer

    '// First test using UCASE to convert text with default comparison mode
    Debug.Print "A " & Now();

    tt.StartCounter

    For i = 1 To 10000000
        '// Need to state binary compare explicitly to override Option Compare Text above
        res = InStr(1, UCase("Today's proDuction"), "PROD", vbBinaryCompare) > 0
    Next i

    Debug.Print " [" & tt.TimeElapsed & "]"


    '// Second test using vbTextCompare comparison mode and implicit type conversion
    Debug.Print "B " & Now();

    tt.StartCounter

    For i = 1 To 10000000
        res = InStr(1, "Today's proDuction", "PROD", vbTextCompare)
    Next i


    Debug.Print " [" & tt.TimeElapsed & "]"


    '// Third test using vbTextCompare comparison mode and explicit test to convert to boolean
    Debug.Print "C " & Now();

    tt.StartCounter

    For i = 1 To 10000000
        res = InStr(1, "Today's proDuction", "PROD", vbTextCompare) > 0
    Next i

    Debug.Print " [" & tt.TimeElapsed & "]"



    '// Fourth test using vbTextCompare comparison mode and explicit type conversion
    Debug.Print "D " & Now();

    tt.StartCounter

    For i = 1 To 10000000
        res = CBool(InStr(1, "Today's proDuction", "PROD", vbTextCompare))
    Next i

    Debug.Print " [" & tt.TimeElapsed & "]"

    '// Fourth test using like
    Debug.Print "E " & Now();

    tt.StartCounter

    For i = 1 To 10000000
        res = "Today's proDuction" Like "*PROD*"
    Next i

    Debug.Print " [" & tt.TimeElapsed & "]"
End Sub

这是一个典型的结果,在许多测试运行中非常一致:

A 28/02/2018 14:36:29 [3479.85848592479]
B 28/02/2018 14:36:33 [5145.24250798252]
C 28/02/2018 14:36:38 [5159.0118225338]
D 28/02/2018 14:36:43 [6627.32650697809]
E 28/02/2018 14:36:50 [6042.61252265476]

因此,似乎转换为大写然后使用默认比较模式的INSTR比使用InStr的vbTextCompare比较模式和使用带通配符的Like语法更快地运行。

在大多数情况下,当然,性能上的差异可能并不明显。