Excel vba что такое 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!

Операторы сравнения чисел и строк, ссылок на объекты (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 вы можете ознакомиться в статье Знаки подстановки для шаблонов.

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

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
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]

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!

Понравилась статья? Поделить с друзьями:
  • Excel vba что лист пустой
  • Excel vba чтение файла txt
  • Excel vba чтение текстового файла построчно
  • Excel vba числовое значение или не числовое
  • Excel vba число элементов массива