The VBA Like operator is something so useful I am often surprised how rarely it is used in Excel and Access VBA. I often tend to see the Like operator as the last resort before using Regular Expressions in VBA. It replaces greatly the VBA InStr function when needing to check if a certain substring is present within a certain string. So let’s get right to it!
Here is a simple example of using the Like operator:
Dim val As String: val = "Dog and Cat" If val Like "*Dog*" Then Debug.Print "Found Dog" End If 'Result: "Found Dog"
The Like operator is an easier alternative to VBA Regex which allows you to search for almost any pattern within a string and find matches.
In case you want to not only find check if the string contains a substring but also return the position of the match – best try using the VBA InStr function.
The VBA Like operator is a boolean operator that return True if a string is matched against a certain string pattern.
Debug.Print "Dog and Cat" Like "*Dog*" 'Result: True Debug.Print "Dog and Cat" Like "*Cow*" 'Result: False
VBA Like allows you also to use the following wildcards to replace certain strings or characters:
Wildcard | Description |
---|---|
* | matches any number of characters |
? | matches any 1 character |
[ ] | matches any 1 character specified between the brackets |
– | matches any range of characters e.g. [a-z] matches any non-capital 1 letter of the alphabet |
# | matches any digit character |
The Like operator is not letter case sensitive! In case you need upper/lower case matching use VBA InStr function instead
And that is basically it. Easy right? Let’s see some examples…
VBA Like operator examples
Let us now look at a couple of examples that greatly show all the possibilities of the Like operator:
Matching against letters
If "Animal" Like "[A-Z]*" then Debug.Print "Match: String starting with Capital letter!" End If
Matching against numbers
If "My house number is 22" Like "*##" then Debug.Print "Match: String contains a 2 digit number" End If
Matching a phone number with either dashes or dots
Debug.Print "123-345-678" Like "###[-.]###[-.]###" 'Result: True
Matching a certain string within another string
Debug.Print "fewfwfewfwefdogfefweff" Like "*dog*" 'Result: True
As you can see in the first row we are using the Like Operator similarly as we use other compare operators (=, >, <, <>). The Like operator let’s you validate if a string on the left side of the operator matches the Like expression on the right.
Conculsions on the VBA Like operator
My main take-aways are:
- Use the VBA Like instead of the InStr function to check if a string contains a substring, if you don’t care about the letter case
- Consider using the VBA Like before resorting to VBA Regular Expressions
- Be sure to master string manipulation too!
Операторы сравнения чисел и строк, ссылок на объекты (Is) и строк по шаблону (Like), использующиеся в VBA Excel. Их особенности, примеры вычислений.
Операторы сравнения чисел и строк
Операторы сравнения чисел и строк представлены операторами, состоящими из одного или двух математических знаков равенства и неравенства:
- < – меньше;
- <= – меньше или равно;
- > – больше;
- >= – больше или равно;
- = – равно;
- <> – не равно.
Синтаксис:
Результат = Выражение1 Оператор Выражение2 |
- Результат – любая числовая переменная;
- Выражение – выражение, возвращающее число или строку;
- Оператор – любой оператор сравнения чисел и строк.
Если переменная Результат будет объявлена как Boolean (или Variant), она будет возвращать значения False и True. Числовые переменные других типов будут возвращать значения 0 (False) и -1 (True).
Операторы сравнения чисел и строк работают с двумя числами или двумя строками. При сравнении числа со строкой или строки с числом, VBA Excel сгенерирует ошибку Type Mismatch (несоответствие типов данных):
Sub Primer1() On Error GoTo Instr Dim myRes As Boolean ‘Сравниваем строку с числом myRes = «пять» > 3 Instr: If Err.Description <> «» Then MsgBox «Произошла ошибка: « & Err.Description End If End Sub |
Сравнение строк начинается с их первых символов. Если они оказываются равны, сравниваются следующие символы. И так до тех пор, пока символы не окажутся разными или одна или обе строки не закончатся.
Значения буквенных символов увеличиваются в алфавитном порядке, причем сначала идут все заглавные (прописные) буквы, затем строчные. Если необходимо сравнить длины строк, используйте функцию Len.
myRes = «семь» > «восемь» ‘myRes = True myRes = «Семь» > «восемь» ‘myRes = False myRes = Len(«семь») > Len(«восемь») ‘myRes = False |
Оператор Is – сравнение ссылок на объекты
Оператор Is предназначен для сравнения двух переменных со ссылками на объекты.
Синтаксис:
Результат = Объект1 Is Объект2 |
- Результат – любая числовая переменная;
- Объект – переменная со ссылкой на любой объект.
Если обе переменные Объект1 и Объект2 ссылаются на один и тот же объект, Результат примет значение True. В противном случае результатом будет False.
Set myObj1 = ThisWorkbook Set myObj2 = Sheets(1) Set myObj3 = myObj1 Set myObj4 = Sheets(1) myRes = myObj1 Is myObj2 ‘myRes = False myRes = myObj1 Is myObj3 ‘myRes = True myRes = myObj2 Is myObj4 ‘myRes = True |
По-другому ведут себя ссылки на диапазоны ячеек. При присвоении ссылок на один и тот же диапазон нескольким переменным, в памяти создаются уникальные записи для каждой переменной.
Set myObj1 = Range(«A1:D4») Set myObj2 = Range(«A1:D4») Set myObj3 = myObj1 myRes = myObj1 Is myObj2 ‘myRes = False myRes = myObj1 Is myObj3 ‘myRes = True |
Оператор Like – сравнение строк по шаблону
Оператор Like предназначен для сравнения одной строки с другой по шаблону.
Синтаксис:
Результат = Выражение Like Шаблон |
- Результат – любая числовая переменная;
- Выражение – любое выражение, возвращающее строку;
- Шаблон – любое строковое выражение, которое может содержать знаки подстановки.
Строка, возвращенная аргументом Выражение, сравнивается со строкой, возвращенной аргументом Шаблон. Если обе строки совпадают, переменной Результат присваивается значение True, иначе – False.
myRes = «восемь» Like «семь» ‘myRes = False myRes = «восемь» Like «*семь» ‘myRes = True myRes = «Куда идет король» Like «идет» ‘myRes = False myRes = «Куда идет король» Like «*идет*» ‘myRes = True |
Со знаками подстановки для оператора Like вы можете ознакомиться в статье Знаки подстановки для шаблонов.
In VBA, you can compare two strings using the Like operator to check matching of the strings. In this tutorial, you will learn how to use this operator with different patterns.
If you want to learn how to compare strings in VBA, click here: VBA Compare Strings – StrComp
If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More
Using the Like Operator to Compare Two Strings
With Like operator, we can check if a string begins with a specific text, includes it, etc. By default, the Like operator compares characters using the Binary method. This means that the operator is case-sensitive. If you want to make it case-insensitive, you need to put Option Compare Text at the top of your module. Using this method, the Like operator considers “S” and “s” the same characters. In our examples, we will use the default, case-sensitive comparison.
If the matching exists, the Like operator returns True as a result, or False otherwise.
First, we will look at the simple example where we want to check if our string variable begins with Mr. To do this, you need to put an asterisk (*) at the end of the matching text (Mr*). Here is the code:
Sub LikeDemo()
Dim strName As String
Dim blnResult As Boolean
strName = "Mr. Michael James"
If strName Like "Mr*" Then
blnResult = True
Else
blnResult = False
End If
End Sub
In this example, we want to check if string strName begins with Mr and return True or False in the variable blnResult.
First, we set the value of strName to Mr. Michael James:
strName = "Mr. Michael James"
Then we use the Like operator in the If statement:
If strName Like "Mr*" Then
blnResult = True
Else
blnResult = False
End If
As the strName begins with Mr, the blnResult returns True:
Image 1. Using the Like operator to check if the string begins with certain characters
Using the Like Operator with Different Matching Patterns
The Like operator can check matching of two strings based on different patterns. Here is the list of possible matching patterns:
Pattern code |
Type of matching |
* |
Matches 0 or more characters |
? |
Matches a single character |
# |
Matches a single digit |
[chars] |
Matches a single character from a char list |
[A-Z] |
Matches any uppercase character from the alphabet |
[A-Za-z] |
Matches any character from the alphabet |
[!chars] |
Matches a single character excluding a char list |
Now we can see how to use these patterns in the code. Here is the example for multiple patterns:
Matching a single character:
strText1 = "ABCDE"
If strText1 Like "AB?DE" Then
blnResult1 = True
Else
blnResult1 = False
End If
Matching a single digit:
strText2 = "AB7DE"
If strText2 Like "AB#DE" Then
blnResult2 = True
Else
blnResult2 = False
End If
Matching any uppercase character from the alphabet:
strText3 = "ABCDE"
If strText3 Like "AB[A-Z]DE" Then
blnResult3 = True
Else
blnResult3 = False
End If
Not matching any uppercase character from the alphabet:
strText4 = "AB7DE"
If strText4 Like "AB[!A-Z]DE" Then
blnResult4 = True
Else
blnResult4 = False
End If
Matching any character from the alphabet (uppercase or lowercase):
strText5 = "ABcDE"
If strText5 Like "AB[A-Za-z]DE" Then
blnResult5 = True
Else
blnResult5 = False
End If
When you execute the code, you can see that the Like operator returns True in blnResult variables for every comparison:
Image 2. Using the Like operator with different matching patterns
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Introduction to VBA Like
VBA Like is used when we have some special characters, spaces in the string and we need to get exact or most relevant output from that word. VBA Like allows us to match the pattern in alphabetical sequence so that if any word contains some special characters then with the help of VBA Like we can complete word. We can also determine if that string is in the proper format or not.
In VBA Like, we have some conditions on that basis we can define what we need to get and how we need to fill the space of missing blank words.
- Question Mark (?) – By this, we can match only one character from the string. Suppose we have string “TAT” and the pattern is “T?T” then VBA Like will return TRUE. If we have the string as “TOILET” and the pattern is still “T?T” then VBA Like will return FALSE.
- Asterisk (*) – By this, we can match 0 or more characters. Suppose we have the string as “L**K” then VBA Like will return TRUE.
- [Char-Char] – By this, we can match any single character in the range Char-Char.
- [!Char] – By this, we can match any single character but not in the list.
- [!Char-Char] – By this, we can match any single character but not in Char-Char.
How to Use VBA Like Function in Excel?
We will learn how to use a VBA Like function with a few examples in excel.
You can download this VBA Like Excel Template here – VBA Like Excel Template
Example #1 – VBA Like
To find if the available string is TRUE or FALSE for VBA Like first, we need a module. For that,
Step 1: Go to Insert menu and click on Module option from the list as shown below.
Step 2: Now in the opened window of Module in VBA, write the subcategory of VBA Like as shown below.
Code:
Sub VBA_Like() End Sub
Step 3: Now first, we will define a variable A as String as shown below. Here, we can use the Long variable as well as it too allows to store any text value in it.
Code:
Sub VBA_Like() Dim A As String End Sub
Step 4: Next, we will assign a word to variable A. Let’s consider that word as “LIKE”.
Code:
Sub VBA_Like() Dim A As String A = "Like" End Sub
Step 5: Now with the help of If-End If loop we will create VBA Like condition.
Code:
Sub VBA_Like() Dim A As String A = "Like" If End If End Sub
We will use the above code in the upcoming example as well directly.
Step 6: Now in If-End If loop write the condition as variable A like “L?KE” is a TRUE condition then give us Yes in a message box or else give us No in the message box for FALSE.
Code:
Sub VBA_Like() Dim A As String A = "Like" If A Like "L?KE" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
We have kept a question mark in the second position. But this can be kept anywhere in whole string.
Step 7: Now compile the code and run it by clicking on the Play button which is available below the menu bar.
We will get the message box as NO. Which means, the word which chose “LIKE” in variable A may have other alphabets in place of a question mark and instead of only “I”.
Example #2 – VBA Like
In this example, we will implement Asterisk (*)
Step 1: Now we will use the same code structure which we have seen in example-1 with the same word “LIKE”.
Code:
Sub VBA_Like2() Dim A As String A = "LIKE" If End If End Sub
Step 2: As we know that with Asterisk we have a match 0 or more characters from any string. So in If-End If loop we will write, if VBA Like matches “*Like*” is TRUE then we will get the message as Yes, else we will get No if it is FALSE.
Code:
Sub VBA_Like2() Dim A As String A = "LIKE" If A Like "*Like*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
Step 3: Again compile the complete code and run it. We will get the message as NO because VBA Like is failed to match any alphabet apart from defined string “Like”.
Step 4: Now if we change the string A from “Like” to “Like Wise” and try to match any letter from the string, let’s say it is “W” in asterisk then what will we get?
As said above, we have used “LIKE WISE” as our new string.
Code:
Sub VBA_Like2() Dim A As String A = "LIKE WISE" If A Like "*W*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
Step 5: Now compile the code and run it again. We will get the message as YES. Which means that VBA Like is able to match any alphabet from our string “LIKE WISE”.
In the same manner, if we match any other letter from “LIKE WISE” we may get the same results.
Example #3 – VBA Like
In this example, we will see, how Char-Char works in matching the strings of characters.
Step 1: For this also, we will use the same frame of code which we have seen in example-2 for defined variable A as “LIKE WISE”.
Code:
Sub VBA_Like4() Dim A As String A = "LIKE WISE" If End If End Sub
Step 2: In if-End If loop, write the condition VBA Like matches letters from I to K (In Asterisk and Char) then it will be TRUE and give us the message as YES. If not then it will be FALSE and we will get the message as NO.
Code:
Sub VBA_Like4() Dim A As String A = "LIKE WISE" If A Like "*[I-K]*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
Step 3: Again compile the code and run it. We will see, VBA Like is able to match the characters from letter I to K and gave us the message as YES.
Pros and Cons of VBA Like
- In a set of database where it is quite frequent to see such special characters, there using VBA Like will allow us to frame hidden words.
- As it has very limited application, so it is very rarely used.
Things to Remember
- We can compare and match only strings. Any other variables such as integers, double cannot be used.
- It is not recommended to record a macro on VBA Like. As we don’t know any excel function on it. And also, doing this process with other ways may result in getting incorrect match results.
- Though VBA Like is very rarely used, but the kind of output it gives may not be accurately given by other functions and command of the same type.
- Save the file in Macro Enable Excel file format only. This format is mainly used when we create any macro.
Recommended Articles
This is a guide to VBA Like. Here we discuss how to use Excel VBA Like function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA InStr
- VBA Integer
- VBA Select Cell
- VBA Transpose
VBA Like Operator
Like is an operator in VBA. A comparison operator compares a given string as an argument in a set of strings and matches the pattern. If the pattern matches, the result obtained is “True,” and if the pattern does not match, then the result obtained is “False.” It is an inbuilt operator in VBA.
LIKE operator is the most underused operator despite its wonderful usage. We have not seen many people who use this operator to a full extent in their coding. One may be the one who does not use this operator quite often. The VBA LIKE operator allows us to match the pattern of the string against the full string. We can compare two strings against the pattern using the VBA LIKE operator. We can check whether the string contains a substring in VBAVBA SubString is a crucial function used for splitting the data by dividing a VBA string into different substrings. There are three types of substring functions available in VBA, i.e., left-right, mid and split functions.read more or whether the string contains any specific format. If the pattern matches the string, then the VBA LIKE operator returns TRUE or else FALSE.
Table of contents
- VBA Like Operator
- Examples of VBA LIKE Operator
- Example #1 – With Question Mark
- Example #2 – With Asterisk
- Example #3 – With Brackets []
- Example #4 – With Brackets & Alphabets [A-Z]
- Recommended Articles
- Examples of VBA LIKE Operator
While matching strings, we need to use wildcard characters to the pattern we specify. Below are the wildcards we use in VBA LIKE operator
- Question Mark (?): One may use it to match any one character from the string. For example, if we have a string “CAT,” and the pattern is “C?T,” then VBA LIKE operator returns TRUE. On the other hand, if the string is “CATCH and the patterns are “C?T,” then VBA LIKE operator returns FALSE.
- Asterisk (*): This matches zero or more characters. For example, if the string is “Good,” and the pattern is “G**d,” VBA LIKE operator returns TRUE.
- Brackets ([]): This matches any single character specified in the brackets.
- [Char-Char]: This matches any single character in the range Char-Char.
- [!Chars]: This matches any single character not in the list.
- [!Char-Char]: This matches any single character not in the range Char-Char.
Examples of VBA LIKE Operator
Let us see some of the examples of VBA LIKE operators now.
You can download this VBA Like Excel Template here – VBA Like Excel Template
Example #1 – With Question Mark
Code:
Sub QuestionMark_Example1() Dim k As String k = "Good" If k Like "Go?d" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
In the above code, we have supplied the string as “Good,” and the pattern is “Go?d.” Since the question mark can match a single character, it will show the result as “Yes.”
Now, we will change the string to “Good Morning.”
Code:
Sub QuestionMark_Example1() Dim k As String k = "Good Morning" If k Like "Go?d" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
In this case, it will show “No” because we have added one more word to the string, i.e., Morning. To match any number of characters, we need to use the asterisk.
Example #2 – With Asterisk
Code:
Sub QuestionMark_Example2() Dim k As String k = "Good Morning" If k Like "*Good*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
In the above example, we have added two asterisks before and after the character “*Good*.” It will match the word “Good” in the string “Good Morning” and return “Yes.”
Example #3 – With Brackets []
Code:
Sub QuestionMark_Example3() Dim k As String k = "Good Morning" If k Like "*[M]*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
The above code matches the single letter mentioned in the bracket “M” and returns the result as “Yes.”
Example #4 – With Brackets & Alphabets [A-Z]
Code:
Sub QuestionMark_Example4() Dim k As String k = "Good Morning" If k Like "*[A-D]*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
In the above, we have mentioned the characters to match from A to D.
It will return “No” because there are no characters from A to D in the string “Good Morning.”
Now, we will change the pattern to [A-H].
Code:
Sub QuestionMark_Example4() Dim k As String k = "Good Morning" If k Like "*[A-H]*" Then MsgBox "Yes" Else MsgBox "No" End If End Sub
It will return “Yes” because from A to H, we have a character “G” in the string “Good Morning.”
Like this, we can use the VBA “LIKE” operator to match any string from the pattern with wildcard characters.
Recommended Articles
This article has been a guide to VBA LIKE. Here, we will take through how to use the VBA LIKE operator, a question mark, asterisk, brackets, and alphabets along with examples and download an Excel template. You may also have a look at other articles related to Excel VBA: –
- Excel VBA CStr Function
- Boolean in VBA
- Right Function in VBA
- For Each Loop in VBA
- VBA ISNULL