Question posted 2013 · +28 upvotes
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?
Accepted answer +53 upvotes
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.
2 code variants in this answer
- Variant 1 — 3 lines, starts with
If InStr(1, "Hello World", "Hello W") = 1 Then - Variant 2 — 3 lines, starts with
If "Hello World" Like "Hello W*" Then
Top vba Q&A (6)
- Difference between Visual Basic 6.0 and VBA +122 (2009)
- VBA – how to conditionally skip a for loop iteration +116 (2011)
- html parsing of cricinfo scorecards +47 (2012)
- Code to loop through all records in MS Access +46 (2011)
- Access VBA | How to replace parts of a string with another string +44 (2011)
- VBA Check if variable is empty +44 (2010)
vba solutions on this site
— top 4%.