How To Easily Extract From Any String Without Using VBA InStr
How To Easily Extract From Any String Without Using VBA InStr
Webinars About
The VBA InStr function is one of the most used functions in VBA. It is used to find a string
within a string and indeed it does a very fine job.
However, it is often used to help extract part of a string and for this task it performs badly.
If you have found string extraction in VBA to be a painful process, then read on. This post
will show you a simpler and better way using three real world examples!
Contents [hide]
If you would like to know more about the InStr or InStrRev functions then please read
Searching within a string.
If you would like to know more about Mid, Left or Right functions then check out
Extracting Part of a String.
For more about the Split function check out String to Array using Split.
I use Debug.Print in my examples. It prints values to the Immediate Window which you
can view by pressing Ctrl and G (or select View->Immediate Window)
Introduction
In this post, I’m going to show you a better way to extract values from a string than using
then VBA InStr function with Left, Right or Mid.
' https://excelmacromastery.com/
Sub ExtractString()
End Sub
These three functions work fine if the text you require is always the same size and in the
same place. For other scenarios, they require the use of InStr to find a particular position
in the string. This makes using them complicated.
Use Left, Right or Mid when the characters will always be in the same
position.
Brooke Hilt
Pamela Jurado
Zack Kinzel
Eddy Wormley
Kaitlyn Rainer
Jacque Trickett
Kandra Stanbery
Margo Hoppes
Berenice Meier
Garrett Hyre
We use the VBA InStr function to get the position of the first space. We want to get all the
characters before the space. We subtract one from the position as this gives us the
position of the last letter of the name.
' https://excelmacromastery.com/
Sub GetFirstname()
s = "Lorraine Huggard"
' Prints Lorraine
lPosition = InStr(s, " ") - 1
Debug.Print Left(s, lPosition)
End Sub
Let’s look at the first example in the above code. The first space is at position 5. We
substract 1 so which gives us position 4. This is the position of the last letter of John i.e.n.
We then give 4 to the Left function and it returns the first four characters e.g. “John”
We can perform the same task in one line by passing the return value from InStr to the
Left function.
Dim s As String
s = "John Henry Smith"
It’s important to note that InStrRev gives us the position from the start of the string .
Therefore, we need to use it slightly differently than we used InStr and Left.
' https://excelmacromastery.com/
Sub GetLastName()
End Sub
' https://excelmacromastery.com/
Sub GetSecondName()
End Sub
You can see this is tricky to do and requires a bit of effort to figure out. We need to find the
first space. Then we need to find the second space. Then we have to substract one from
the other to give us the number of characters to take.
If have a string with a lot of words then this can get very tricky indeed. Luckily for us there
is a much easier was to extract characters from a string. It’s called the Split function.
Let’s try the same three examples again and this time we will use Split.
Boom! What a difference using Split makes. The way it works is as follows
The following table shows what the array might look like after Split has been used.
Note: the first position in the array is zero. Having zero based arrays is standard in
programming languages.
0 1 2
In the above code we split the string each time we used it. We could also split the string
once and store it in an array variable. Then we can access it when we want.
' https://excelmacromastery.com/
Sub SplitName()
Dim s As String: s = "John Henry Smith"
Dim arr() As String
arr = Split(s, " ")
If you would like to know more about arrays then I wrote an entire post about them called
The Complete Guide to Using Arrays in Excel VBA.
In the next sections, we will look at some real-world examples. You will see the benefit of
using Split instead of the InStr function.
Please feel free to try these yourself first. It is a great way to learn and you may have fun
trying to figure them out(or maybe that’s just me!)
“VB_23476_Val.xls”
“VV_987_Val.txt”
“VZZA_12223_Val.doc”
This is similar to the example of where we get the second item. To get the values here we
use the underscore(i.e. “_”) to split the string. See the code example below
' https://excelmacromastery.com/
Sub GetNumber()
In the real world you would normally read strings like these from a range of cells. So let’s
say these filenames are stored in cells A1 to A3. We will adjust the code above slightly to
give us:
' https://excelmacromastery.com/
Sub ReadNumber()
Dim c As Range
For Each c In Range("A1:A3")
' Split each item as you read it
Debug.Print Split(c, "_")(1)
Next c
End Sub
The user has a string with an IP address in the format “BE-ABCDDD-DDS 172.16.23.3”.
This is how I would do this. First I split the string by the periods. The number we are
looking for is between the first and second period. Therefore, it is the second item. When
we split the string it is placed at position one in the array (remember that the array starts
at position zero).
0 1 2 3
BE-ABCDDD-DDS 172 31 23 3
The code below shows how to do this
' https://excelmacromastery.com/
Sub IPAdd()
End Sub
Filename Status
AA1234.pdf valid
AA_ljgslf_1234.pdf valid
12_AA_1234_NM.pdf Valid
End Sub
This code is very messy. Luckily for us, VBA has Pattern Matching. We can check the pattern
of a string without having to search for items and positions etc. We use the Like operator
in VBA for pattern matching. The example below shows how to do it.
' https://excelmacromastery.com/
Sub UsePattern()
End Sub
In the above example, the asterisk in the pattern refers to any number of characters.
To show this works correctly, let’s try it on all the example names in the table
' https://excelmacromastery.com/
Sub UsePatternTest()
End Sub
The output is
True
True
False
False
True
To find out more about Pattern Matching and the Like keyword please check out this post.
Conclusion
InStr and InStrRev are really only useful for simple tasks like checking if text exists in a
string.
Left, Right and Mid are useful when the position of the text is always the same.
The Split function is the best way to extract from a variable string.
When trying to check the format of a string that is not fixed in size, the Like keyword(i.e.
Pattern Matching) will generally provide an easier solution.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills
then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA
applications from scratch.)
If you are serious about mastering VBA then you may want to check out The Excel VBA
Handbook
27 Comments
Gerhard Pundt on September 23, 2015 at 11:36 am
Hallo Paul,
what a great post about this problem.
I learned a lot this.
Now I will use cost of subscription with RSS.
Greatings
Gerhard
Reply
Paul
Reply
Hey, John here whatever you shared online its really great
Not only for vba programmers but also non vba
programmers
I really thank you to for such great work you have done
Reply
Regards
Paul
Reply
Bruce Collins on November 22, 2015 at 9:10 pm
Extraordinary resource – clearly written and on point.
I today incorporated your Split approach in a previous function that had
used InStr. Function is repeatedly called, however, and I am curious if there
is any need to clear the identical array created in Split after each use.
Cannot find a name associated with array created in Split. (Assume name
would be necessary for using Erase).
Reply
This code uses Split once and stores the result to an array.
[sourcecode language=”vb”]
Sub SplitName()
Dim s As String: s = "John Henry Smith"
Dim arr() As String
arr = Split(s, " ")
Debug.Print arr(0) ‘ John
Debug.Print arr(1) ‘ Henry
Debug.Print arr(2) ‘ Smith
End Sub
[/sourcecode]
[sourcecode language=”vb”]
Sub SplitNameWithErase()
Dim s As String
Dim arr() As String
Dim c As Range
For Each c In Range("A1:A5000")
arr = Split(c, " ")
Erase arr
Next c
End Sub
[/sourcecode]
Reply
Reply
Dim c As Range
Dim arr() As String
Dim i As Integer
Reply
Jim Fisher on December 29, 2015 at 4:20 pm
HI Paul,
Paul,
This site is a great resource. I appreciate your work and I’m glad I stumbled
across it.
Using the SPLIT technique (which is awesome) how do you extract just the
first name from a list of names that may or may not have last or middle
names? I’ve got a worksheet containing a list of contact names that is edited
by several people. Some names have only a first name. Some have first and
last and a few have first, middle and last.
Reply
Reply
David Moore on January 27, 2016 at 3:27 pm
Paul, really great post. I have used the InStr with Mid method for a long
time, and never thought of using split like this. Also you have a great site
here with a lot of great information. Thanks!
Reply
Reply
Reply
Hi Paul,
Good post again!
The result of your Sub UsePattern should be True instead of False
Reply
Paul Kelly on April 27, 2017 at 3:33 am
Thanks Dany, I updated the code.
Reply
jade on March 12, 2018 at 7:17 pm
I need to check a specific text in website and print the result if it matches
the whole word.
FOR EXAMPLE
i need to check “red” in aaaaaa.com and print only if red is present. i used
INSTR but it scrapes from the word occured
,undelivered,semiretired,unchartered,unconquered…..
Reply
Reply
I Have an Excel Database of nearly 4,500 songs of the 60’s, 70’s, 80’s and
90’s, chronologically and alphabetically sorted as are the mp3 files, eg…
I can currently parse the above through to the Windows Object library, but
only one mp3 at a time.
Below is my code. (Please forgive me, but I am only a beginner, but quickly
turning into a VBA addict).
Geoff
Sub PlaySong()
DriveName = Range(“L3”).Text
FullPathSongTitle = DriveName & "\" & Decade & "\" & Year & "\" &
MP3_Title
ActiveSheet.OLEObjects.Add(Filename:=FullPathSongTitle,
Link:=True).Select
If Err.Number 0 Then
msgbox “Cannot Locate…” & vbNewLine & FullPathSongTitle,
vbExclamation, ” ERROR!”
Range(CurrentCell).Select
Exit Sub
End If
Selection.Verb: Selection.Delete
Range(CurrentCell).Select
End Sub
Reply
Reply
Richard on October 31, 2018 at 4:00 pm
Outstanding resource… this page has quickly become a “go to” for
understanding VBA principles. Rarely do you find explanations that are
clear enough that they make sense to someone that doesn’t specialize in
this field.
Thank you for all your efforts Paul! Keep up the fantastic work!
Reply
Reply
Reply
Reply
Reply
Michael on October 11, 2020 at 10:10 pm
Hi Paul,
You have a lot of great information here. What if you are trying to find the
set up numbers in a text string that are in groups in 2-3 locations? i.e. “This
is 33D54=7500 to finish”. I need to split these up into 3 sets of numbers.
Reply
1) Go through the string and replace all the chars out of the ASCII range
[48:57] with particular symbol e.g. “|”
2) In case it can be more than 1 non-numeric char between your numbers –
replace all “||” with “|”
3) use Split function with “|” as the splitter
Reply
Reply
You are not logged in
You are not currently logged in.
Username or Email Address:
Password:
Remember Me
Login
» Register
» Lost your Password?
Designed by Elegant Themes | Powered by WordPress