测试字符串是否以字符串开头?

arm*_*rhb 66 vba

在VBA中,测试字符串是否以子字符串开头的最直接的方法是什么?Java有startsWith.有VBA等价吗?

arm*_*rhb 120

做这件事有很多种方法:

InStr函数

您可以使用InStr内置函数来测试String是否包含子字符串. InStr将返回第一个匹配的索引,或0.因此,您可以通过执行以下操作来测试String是否以子字符串开头:

If InStr(1, "Hello World", "Hello W") = 1 Then
    MsgBox "Yep, this string begins with Hello W!"
End If
Run Code Online (Sandbox Code Playgroud)

如果InStr返回1,则String("Hello World")以子字符串("Hello W")开头.

喜欢

您还可以使用like比较运算符以及一些基本模式匹配:

If "Hello World" Like "Hello W*" Then
    MsgBox "Yep, this string begins with Hello W!"
End If
Run Code Online (Sandbox Code Playgroud)

在这里,我们使用星号(*)来测试String是否以我们的子字符串开头.


Bla*_*awk 35

根据Java函数声明和描述来startsWith判断,在VBA中实现它的"最直接的方法"是Left:

Public Function startsWith(str As String, prefix As String) As Boolean
    startsWith = Left(str, Len(prefix)) = prefix
End Function
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望偏移参数可用,请使用Mid:

Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
    startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function
Run Code Online (Sandbox Code Playgroud)

  • 这也比armtrhb的解决方案更快地执行(他的解决方案更容易阅读和编码). (3认同)
  • 您还可以使用 Mid$(...) 函数或 Left$(...) 函数(允许直接传递字符串变量而无需将其包装在 Variant 中)来加快速度 (2认同)