In VBA, what's the most straight forward way to test if a string begins with a substring? Java has startsWith
. Is there a VBA equivalent?
Python String startswith()The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .
Java String startsWith() Method The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).
We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.
Check if String starts with a Letter using isapha() In Python, the string class provides a function isalpha(). It returns True if all the characters in the string are alphabetic and at least one character in the string. We can use this to check if a string starts with a letter.
There are several ways to do this:
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").
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With