Test if string begins with a string?
Judging by the declaration and description of the startsWith
Java function, the "most straight forward way" to implement it in VBA would either be with Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
Or, if you want to have the offset parameter available, with 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
There are several ways to do this:
InStr
You can use the InStr
build-in function to test if a String contains a substring. InStr
will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:
If InStr(1, "Hello World", "Hello W") = 1 Then
MsgBox "Yep, this string begins with Hello W!"
End If
If InStr
returns 1
, then the String ("Hello World"), begins with the substring ("Hello W").
Like
You can also use the like
comparison operator along with some basic pattern matching:
If "Hello World" Like "Hello W*" Then
MsgBox "Yep, this string begins with Hello W!"
End If
In this, we use an asterisk (*) to test if the String begins with our substring.