Vba excel оператор like

Операторы сравнения чисел и строк, ссылок на объекты (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:

vba like operator begins with

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:

vba like operator different matching patterns

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!
vba save as

Learn More!

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

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.

VBA Like

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Like (wallstreetmojo.com)

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.”

VBA LIKE Example 1

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.

VBA LIKE Example 1-1

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.”

VBA LIKE Example 2

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.”

VBA LIKE Example 3

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.”

Brackets & Alphabets Example 4

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.”

Brackets & Alphabets Example 4-1

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

vba like operator

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!

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Like operator

vblr6.chm1008961

vblr6.chm1008961

office

6df80925-8331-6c8c-4fd3-f397de0e44c1

11/19/2018

medium

Used to compare two strings.

Syntax

result = string Like pattern

The Like operator syntax has these parts:

Part Description
result Required; any numeric variable.
string Required; any string expression.
pattern Required; any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks

If string matches pattern, result is True; if there is no match, result is False. If either string or pattern is Null, result is Null.

The behavior of the Like operator depends on the Option Compare statement. The default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. Sort order is determined by the code page.

In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive, textual sort order determined by your system’s locale. When you sort the same characters using Option Compare Text, the following text sort order is produced:

(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Characters in pattern Matches in string
? Any single character.
* Zero or more characters.
# Any single digit (0-9).
[ charlist ] Any single character in charlist.
[ !charlist ] Any single character not in charlist.

A group of one or more characters ( charlist ) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

[!NOTE]
To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can’t be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen () to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A-Z. Multiple ranges are included within the brackets without delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the Option Compare Binary example, the range [A-E] matches A, B and E. With Option Compare Text, [A-E] matches A, a, À, à, B, b, E, e. The range does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

  • An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.
  • A hyphen () can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.
  • When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.
  • The character sequence [] is considered a zero-length string («»).

In some languages, there are special characters in the alphabet that represent two separate characters. For example, several languages use the character «æ» to represent the characters «a» and «e» when they appear together. The Like operator recognizes that the single special character and the two individual characters are equivalent.

When a language that uses a special character is specified in the system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in string.

Example

This example uses the Like operator to compare a string to a pattern.

Dim MyCheck
MyCheck = "aBBBa" Like "a*a"    ' Returns True.
MyCheck = "F" Like "[A-Z]"    ' Returns True.
MyCheck = "F" Like "[!A-Z]"    ' Returns False.
MyCheck = "a2a" Like "a#a"    ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]"    ' Returns True.
MyCheck = "BAT123khg" Like "B?T*"    ' Returns True.
MyCheck = "CAT123khg" Like "B?T*"    ' Returns False.
MyCheck = "ab" Like "a*b"    ' Returns True.
MyCheck = "a*b" Like "a [*]b"    ' Returns False.
MyCheck = "axxxxxb" Like "a [*]b"    ' Returns False.
MyCheck = "a [xyz" Like "a [[]*"    ' Returns True.
MyCheck = "a [xyz" Like "a [*"    ' Throws Error 93 (invalid pattern string).

See also

  • Operator summary

[!includeSupport and feedback]

Excel VBA Like

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.

Module VBA Like

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

VBA Like Example 1.1

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

VBA Like Example 1.2

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

VBA Like Example 1.3

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

VBA Like Example 1.4

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

 Example 1.5

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.

VBA Like 1

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

VBA Like Example 2.1

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

Example 2.2

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”.

VBA File 2

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

Example 2.3

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”.

VBA File 3

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

Example 3.1

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

Example 3.2

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.

VBA Life 4

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 –

  1. VBA InStr
  2. VBA Integer
  3. VBA Select Cell
  4. VBA Transpose

Author: Oscar Cronquist Article last updated on February 07, 2023

LIKE operator

The LIKE operator allows you to match a string to a pattern using Excel VBA. The image above demonstrates a macro that uses the LIKE operator to match a string to a given pattern.

The pattern is built on specific characters that I will demonstrate below.

Excel VBA Function Syntax

result = string Like pattern

Arguments

result Required. Any number.
string Required. A string.
pattern Required. A string that meets the required pattern characters described below.

What’s on this webpage

  1. What characters can you use as a pattern?
    1. How to make the LIKE operator case insensitive?
    2. What does the LIKE operator return?
  2. Compare a cell value to a pattern
    1. How to use the question mark (?)
    2. How to use the asterisk (*)
    3. How to use the number sign or hashtag (#)
    4. Combining pattern characters
    5. How to use brackets
  3. Search for a regex pattern and extract matching values (UDF)
  4. Search for a regex pattern and return values in an adjacent column (UDF)
  5. Extract words that match a regex pattern from cell range (UDF)
  6. Where to put the code?
  7. Get Excel file

1. What characters can you use as a pattern in the LIKE operator?

The following characters are specifically designed to assist you in building a pattern:

Character Desc Text
? question mark Matches any single character.
* asterisk Matches zero or more characters.
# number or hash sign Any single digit.

A1A* — You can also use a string combined with the characters above to build a pattern. This matches a string beginning with A1A or is equal to A1A. The asterisk matches zero characters as well.

Characters Desc Text
[abc] brackets Characters enclosed in brackets allow you to match any single character in the string.
[!abc] exclamation mark The exclamation mark (!)  matches any single character not in the string.
[A-Z] hyphen The hyphen lets you specify a range of characters.

Back to top

1.1 How to make the LIKE operator case insensitive?

LIKE operator case insensitive

Add Option compare binary or Option compare text before any macros or custom functions in your code module to change how string evaluations are made.

The default setting is Option compare binary. Use Option compare text to make the comparison case-insensitive but put the code in a separate module so other macros/functions are not affected.

Setting Desc
Option compare binary Default.
Option compare text Case-insensitive evaluations.

To learn more, read this article: Option Compare Statement

Back to top

1.2 What does the LIKE operator return?

LIKE operator return boolean

The image above shows a macro in the Visual Basic Editor that returns either TRUE or FALSE depending on if the pattern matches the string or not.

Pattern *1* matches 552513256 and the macro above shows a message box containing value True.

result = string Like pattern

The LIKE operator returns a boolean value, TRUE or FALSE depending on if the pattern is a match or not. You can save the boolean value to a variable, the line above stores the boolean value in the variable result.

Back to top

2. Compare a cell value to a pattern

LIKE operator UDF compare

This simple User Defined Function (UDF) lets you specify a pattern and compare it to a cell value. If there is a match, the function returns TRUE. If not, FALSE. I am going to use this UDF in the examples below.

'Name User Defined Function
'Parameter c declared data type Range
'Parameter pttrn declared data type String
Function Compare(c As Range, pttrn As String) As Boolean

'Evaluate string in variable c with pattern saved to variable pttrn
'Return the result to the User Defined Function
Compare = c Like pttrn
End Function

Copy the code above and paste it to a code module in the VB Editor, if you want to use it. Where to put the code?

We are going to use this User Defined Function to compare patterns with strings located on a worksheet, read the next section.

Back to top

2.1 How to use the question mark (?) character

LIKE operator question mark character

The picture above demonstrates the User Defined Function we created in section 2. It takes the string in column B and compares it to the pattern in column D. A boolean value True or False is returned to column E.

UDF syntax: Compare(string, pattern)

A question mark (?) matches any single character.

Formula in cell E6:

=Compare(B6, D6)

Value in cell B6 ABC matches A?C specified in cell D6, TRUE is returned to cell E6.

Formula in cell E7:

=Compare(B7, D7)

Value in cell B7 ABCD does not match pattern A?D. BC are two characters, a question mark matches any single character. FALSE is returned in cell E3.

Formula in cell E8:

=Compare(B8, D8)

Value in cell B8 ABCD matches the pattern specified in cell D8, ?BC?. TRUE is returned to cell E8.

Back to top

2.2 How to use the asterisk (*) character

LIKE operator asterisk character

The image above demonstrates the User Defined Function (UDF) described in section 2, it evaluates if a pattern matches a string using the LIKE operator. If so returns True. If not, False.

The UDF is entered in cell E9, E10, and E11. The first argument in the Compare UDF is a cell reference to the string and the second argument is a cell reference to the pattern.

Let’s begin with the formula in cell E9:

=Compare(B9, D9)

The pattern tells you that the first three characters must be AAA and then the * (asterisk) matches zero or more characters. AAAC is a match to pattern AAA* and the UDF returns TRUE in cell E9.

Formula in cell E10:

=Compare(B10, D10)

aaa* does not match pattern AAAC. aaa is not equal to AAA. LIKE operator is case sensitive unless you change settings to Option Compare Text.

Formula in cell E11:

=Compare(B10, D10)

(*) matches zero or more characters, DDC23E matches DD*E.

Back to top

2.3 How to use the number sign or hashtag (#) character

LIKE operator hashtag character

The image above shows  patterns in column D and strings in column B, the hashtag character # matches a single digit. To match multiple digits use multiple #.

Formula in cell E3:

=Compare(B3, D3)

String 123 in cell B3 matches pattern 12#, TRUE is returned in cell E3.

Formula in cell E4:

=Compare(B4, D4)

String 123 in cell B4 does not match pattern 1# in cell D4, the hashtag character matches any single digit only.

Formula in cell E5:

=Compare(B5, D5)

String 123 in cell B5 matches the pattern in cell D5 #2#.

Back to top

2.4 Combining pattern characters

LIKE operator combining pattern characters

The following three examples use asterisks, question marks, and number signs combined.

Formula in cell E12:

=Compare(B12, D12)

Pattern *##?? in cell D12 matches string AA23BB in cell B12, the formula returns True in cell E12. The asterisk matches 0 (zero) to any number of characters, the hashtag matches any single digit.

Note that there are two hashtags in the pattern. The ? question mark matches any single character.

Formula in cell E13:

=Compare(B13, D13)

The string in cell B13 AA23BB does not match pattern *##? specified in cell D13. There must be one character after the digits, the string has two characters after the digits.

Formula in cell E14:

=Compare(B13, D13)

The string AA23BB in cell B14 matches the pattern in cell D14 *##*. The asterisk matches 0 (zero) to any number of characters, the hashtags match two single digits and the last pattern character is the asterisk.

Back to top

2.5 How to use brackets with the LIKE operator

LIKE operator brackets

Brackets match any single character you specify. A hyphen lets you compare a range of letters, however, they must be sorted from A to Z. [A-C] is a valid range but [C-A] is not valid.

Formula in cell E15:

=Compare(B15, D15)

The formula in cell E15 evaluates the string ABCD to pattern [A]* and returns TRUE. The first character in the string must be A or a, the number of remaining characters can be zero or any number in length.

Formula in cell E16:

=Compare(B16, D16)

The formula in cell E16 evaluates the string ABCD to pattern [A] and returns FALSE. The string must be only one character and that character must be A or a.

Formula in cell E17:

=Compare(B17, D17)

The formula in cell E17 compares the string ABCD to pattern [!A]* and returns FALSE. The first character in the string must be anything but character A and the number of remaining characters can be 0 (zero) or any number in length.

Formula in cell E18:

=Compare(B18, D18)

The formula in cell E18 compares the string C22R to pattern [A-Z]##? and returns TRUE. The first character in the string must be a letter between A to Z, then any two digits, and lastly a question mark that matches any single character.

Formula in cell E19:

=Compare(B19, D19)

The formula in cell E19 compares the string C22R to pattern [A-Z]##[A-Z] and returns TRUE. The string begins with any letter between A to Z, then any two digits, and lastly, any letter between A to Z.

Formula in cell E20:

=Compare(B20, D20)

The formula in cell E20 compares the string C222 to pattern [A-Z]##[A-Z] and returns FALSE. The string begins with any letter between A to Z, then any two digits, and lastly, any letter between A to Z. The string has a digit as the last character which isn’t a match.

Back to top

3. Search for a regex pattern in column and get matching values (UDF)

Search for a regex pattern in column and get matching values

The following user-defined function allows you to extract cell values using the LIKE operator and a pattern specified on the worksheet.

The formula is entered in cell D6 as an array formula, it returns multiple values to cells below if the pattern matches multiple values.

The example pattern used is in cell D3 «?B?». The question mark matches a single character, the UDF returns all values containing three letters and the middle letter is B.

Array formula in cell D6:D9:

=SearchPattern(B3:B16, D3)

How to enter an array formula

'Name User-defined Function
Function SearchPattern(c As Range, pttrn As String)

'Dimension variables and declare data types
Dim d as String

'Iterate through each cell in c
For Each cell In c

'Check if string matches pttrn, if so concatenate cell value and comma to variable d
If cell Like pttrn Then d = d & cell & ","

'Continue with next cell
Next cell

'Split string in variable d using comma character then transpose array and return values to UDF SearchPattern
SearchPattern = Application.Transpose(Split(d, ","))
End Function

Where to put the code?

Back to top

4. Search for a pattern and return values in an adjacent column (UDF)

Search for a regex pattern in column and get adjacent values on the same rows

This User Defined Function allows you to look for a pattern in a column and return the corresponding value in another column.

The UDF returns a value from column C if the corresponding value in column B on the same row matches the regex pattern specified in cell E3.

Array formula in cell E6:E9:

=SearchCol(B3:B16, C3:C16, E3)

How to enter an array formula

'Name User Defined Function (UDF)
Function SearchCol(b As Range, c As Range, pttrn As String)

'Dimension variables and declare data types
Dim a As Long, d as String

'Count cells in cell range b
a = b.Cells.CountLarge

'For ... Next statement meaning iterate lines in between a times
For i = 1 To a

'Check if cell matches pattern, if so add c and a comma to variable d
If b.Cells(i) Like pttrn Then d = d & c.Cells(i) & ","
Next i

'Split values in variable d and return array to worksheet
SearchCol = Application.Transpose(Split(d, ","))
End Function

Where to put the code?

Back to top

5. Extract words that match a regex pattern from cell range (UDF)

Extract words from cell range if regex pattern matches UDF

The image above demonstrates a User Defined Function (UDF) that extracts words that match a given regex pattern. This means that the UDF may extract multiple words from the same cell.

You can use this UDF to extract phone numbers, zip codes, email addresses, html code, or pretty much anything from cells that contain a lot of data.

Array formula in cell D5:

=ExtractWords(B3:B10,E2)

If you want to split the data using a different character change the space character in the VBA code below to any delimiting character or characters.

5.1 How to enter an array formula

  1. Select the cell range you want to use.
  2. Press with left mouse button on in the formula bar.
  3. Paste array formula to the formula bar.
  4. Press and hold CTRL + SHIFT simultaneously.
  5. Press Enter once.
  6. Release all keys.

Your formula is now an array formula, you recognize array formulas by the beginning and ending curly brackets in the formula bar. {=array_formula}

Don’t enter these characters yourself, they appear automatically.

5.2 VBA code

'Name User Defined Function (UDF)
Function ExtractWords(c As Range, pttrn As String)

'Iterate through each cell in cell range c
For Each cell In c

    'Split cell contents into an array using space as a delimiting character
    Arr = Split(cell, " ")

    'Iterate through each value in array Arr
    For Each a In Arr

        'Check if string in variable a matches pattern in variable pttrn
        If a Like pttrn Then

            'Add string a and a comma to variable d
            d = d & a & ","
        End If
    Next
    
Next cell

'Split variable d using comma as a delimiting character and return array to UDF
ExtractWords = Application.Transpose(Split(d, ","))

End Function

6. Where to put the code?

LIKE operator where to put the code 1

  1. Press Alt+F11 to open the Visual Basic Editor (VBE).
  2. Press with mouse on «Insert» on the top menu, see image above.
  3. A popup menu appears. Press with left mouse button on «Module» to insert a module to your workbook.
  4. Copy the VBA code.
  5. Paste to the code window.
  6. Return to Excel.

Note, save your workbook with file extension *.xlsm (macro-enabled workbook) to attach the code. This step is important.

Did you know?

like-operator-example-9

You can use the question (?)  mark and asterisk (*) characters in many Excel functions. The COUNTIF function in cell C2 demonstrated in the image above counts cells in cell range A2:A15 using the pattern in cell B2.

like-operator-example-10

If you need to use even more complicated patterns Excel allows you to use regular expressions, see this thread:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Back to top

Back to top

Проверка текста по маске

В языке Visual Basic существует один крайне полезный оператор, называемый Like. Он умеет проверять подобие (похожесть) двух текстовых строк. К сожалению, в стандартном наборе функций этот оператор не нашел своего места, но очень легко создать пользовательскую функцию, которая будет это делать.

Откройте редактор Visual Basic, нажав ALT+F11 или выбрав в меню Сервис — Макрос — Редактор Visual Basic (Tools — Macro — Visual Basic Editor), вставьте новый модуль (меню Insert — Module) и скопируйте туда текст этой функции:

Function MaskCompare(txt As String, mask As String, CaseSensitive As Boolean)
    If Not CaseSensitive Then
        txt = UCase(txt)
        mask = UCase(mask)
    End If
        
    If txt Like mask Then
            MaskCompare = True
        Else
            MaskCompare = False
    End If
End Function

Закройте редактор Visual Basic и вернитесь в Excel.

Теперь через Вставка — Функция (Insert — Function) в категории Определенные пользователем (User Defined) можно найти нашу функцию MaskCompare и воспользоваться ей. Синтаксис функции следующий:

=MaskCompare(txt; mask; CaseSensitive)

где

txt — любой текст или ячейка с текстом, которую мы проверяем на соответствие маске

mask — набор символов, которые ищутся в проверяемом тексте. Набор может содержать спецсимволы подстановки:

  • * — любое количество любых символов
  • ? — один любой символ
  • # — любая цифра (0 — 9)
  • [список_символов] — любой символ из списка
  • [!список_символов] — все символы, кроме содержащихся в списке

Case_Sensitive — необходимо ли учитывать регистр при проверке:

  • 1 — регистр символов учитывается
  • 0 — регистр символов не учитывается

Примеры использования функции

Использование спецсимволов в маске открывает перед пользователем широчайшие возможности. Вот несколько примеров масок:

  • ### — все числа от 0 до 999
  • ????? — все слова из 5 букв
  • м*н — все слова, начинающиеся на «м» и заканчивающиеся на «н»
  • *[аостр]* — все слова, содержащие хотя бы одну из букв а,о,с,т,р
  • *[!abcdefghijklmnopqrstuvwxyz]* — все слова НЕ содержащие английских букв

Ссылки по теме

  • Поиск ближайшего похожего слова
  • Что такое макросы, куда вставлять код макроса на VBA, как их использовать

Понравилась статья? Поделить с друзьями:
  • Vba excel оператор if not
  • Vba excel открыть гиперссылку
  • Vba excel открыть все книги в папке
  • Vba excel открыть word документ
  • Vba excel открыть chrome