VBA: Test if string begins with a string?

calendar_today Asked Dec 27, 2013
thumb_up 53 upvotes
history Updated April 16, 2026

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)

+53 upvotes ranks this answer #3 out of 81 vba solutions on this site — top 4%.
vba