Extract Any String Without Using Instr
Extract Any String Without Using Instr
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]
1 A Quick Guide to this Post
2 Quick Reference Notes
3 Introduction
4 When VBA InStr, Left, Right and Mid are useful
o 4.1 Using InStr to check if string contains text
o 4.2 Extracting with Left, Right and Mid
5 Dealing with Strings of Varying Lengths
o 5.1 Using the VBA InStr Function with Left
o 5.2 Using the VBA InStr Function with Right
o 5.3 Using the VBA InStr Function with Mid
6 The Split Function
7 Example 1: Getting part of a file name
8 Example 2: IP Address Range
9 Example 3: Check if a filename is valid
10 Conclusion
11 What’s Next?
12 Get the Free eBook
"John Henry Smith" Variable size get first name Split(s," ")(0)
"John Henry Smith" Variable size get second name Split(s," ")(1)
"John Henry Smith" Variable size get third name Split(s," ")(2)
"John Henry Smith" Variable size Get last name Dim v As Variant
v = Split(s, " ")
lastname= v(UBound(v))
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.
This post is broken down as follows
Debug.Print "Found"
End If
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.
Sub GetFirstname()
s = "Lorraine Huggard"
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
Sub GetLastName()
Dim s As String: s = "John,Henry,Smith"
Length = Len(s)
End Sub
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.
Sub SplitName()
End Sub
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!)
Sub GetNumber()
End Sub
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:
Sub ReadNumber()
Dim c As Range
Next c
End Sub
0 1 2 3
BE-ABCDDD-DDS 172 31 23 3
Sub IPAdd()
End Sub
Example 3: Check if a filename is valid
In this final example, we want to check that a file name is valid. There are three rules
Filename Status
AA1234.pdf valid
AA_ljgslf_1234.pdf valid
12_AA_1234_NM.pdf Valid
Sub UseInstr()
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.
Sub UsePattern()
End Sub
In the above example, the asterisk in the pattern refers to any number of characters.
Let’s break down this pattern *AA*1234*.pdf
* – any group of characters
AA – the exact characters AA
* – any group of characters
1234 – the exact characters 1234
* – any group of characters
.pdf – the exact characters .pdf
To show this works correctly, let’s try it on all the example names in the table
Sub UsePatternTest()
coll.Add "AA1234.pdf"
coll.Add "AA_ljgslf_1234.pdf"
coll.Add "AA1234.pdf1"
coll.Add "12_AA_1234_NM.pdf"
Dim f As Variant
Next f
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.