在VBA中,什么是测试一个字符串的子串开头的最直接的方法是什么? Java有startsWith
。是否有一个VBA等同?
做这件事有很多种方法:
您可以使用InStr
内建函数测试字符串包含的子字符串。 InStr
或者返回索引的第一个比赛,或者0。所以,你可以,如果一个字符串,通过执行以下操作的子测试开始:
If InStr(1, "Hello World", "Hello W") = 1 Then
MsgBox "Yep, this string begins with Hello W!"
End If
如果InStr
返回1
,那么字符串( “Hello World” 的),始于子( “你好W”)。
您也可以使用like
比较操作一些基本的模式匹配一起:
If "Hello World" Like "Hello W*" Then
MsgBox "Yep, this string begins with Hello W!"
End If
在这方面,我们使用星号(*),以测试是否字符串与我们的子开始。
由declaration and description of the startsWith
Java function来看,“最直接的方式”来实现它在VBA要么与Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
或者,如果你想拥有可用的偏移参数,以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