Word vba like not like

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

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

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

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!

In any programming language, there is a way to compare strings against some patterns. Several characters are used to create these patterns. These patterns are called regular expressions.

Like in structured query language, VBA offers the “Like” operator which can help us compare strings against patterns or other strings. This works with wildcard characters.

List of Wildcard Characters

S.no Wild Card Character Description
1 ? ( Question Mark) This is used 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. If the string is “CATCH and the patterns are “C?T,” then VBA LIKE operator returns FALSE.
2 * (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.
3 [] (square brackets) This matches any one single character specified in the brackets.
4 [<single character within a range>] This matches any single character in the range Char-Char.
5 [!<list of single characters>] This matches any single character not in the list.
6 [!<single character within a range>] This matches any single character not in the range Char-Char.
7 # ( hash) This matches any single digit.

Examples of Programs That Use the Like Operator

Example Program: The “*” Wildcard Character

Scenario: A shop offers to give away a pen as a gift to customers who buy any ice cream. We are developing a code that will consider the customers who purchase any item with the words ice and cream in them. For this we will use the asterisk wildcard (*) character.

Sub likeoperator_Demo()
' declare a variable
Dim var_item

' receive input from the customer in the form of item number
var_item = InputBox("Enter the item you wish to buy")

' validate if the product is eligible for free gift. The "*" stands for any number of "any character(s)".
If var_item Like "*ice*cream*" Then
    ' eligible
    Debug.Print "You item '" & var_item & "' is eligible for the free gift - pen"
Else
    ' not eligible
    Debug.Print "You item '" & var_item & "' is not eligible for the free gift - pen"
End If

End Sub

Output for Various Products:

Example of an output for various products.

In this output you might have noticed that only the products with “ice” and “cream” in lower case, with or without any characters in between in the same order (“cream” after “ice”), are eligible for the offer. Any products with “ice”/“cream” alone in their product names are not eligible for the offer.

This shows that the comparison we have done in the “if” conditional clause is “CASE SENSITIVE.”

To make my module case-insensitive i.e. to consider both capital and small letters, the statement “OPTION COMPARE TEXT” has to be used on top of the module.

Option Compare Text

Example of option compare text
This image clearly shows how the same technique worked without the case sensitivity issue.

Example Program: The “?” Wildcard

Here is a simple program with a “?” (question mark) in a word. This is treated as a pattern and compared with input text. Let us run this code without the “Option compare text” to see original results.

Sub wildcard_like_demo()

' declare a string variable and an input variable
Dim pattern1, var_input

' initialize te variable with one "?" character which can accept any character in it place to say that it matches this variable
pattern1 = "SCHOOL?BOY"
' literally we have made pattern1 a pattern.
  
' receive an input from the user and store it in var_input variable
var_input = InputBox("Enter a text. ")

'compare to see if there is any single character in the place of "?"
If var_input Like pattern1 Then

' if so, the input  matches the pattern
    Debug.Print "The input text '" & var_input & "' matches the pattern '" & pattern1 & "'"
Else

' if not, the input does not match the pattern
    Debug.Print "The input text '" & var_input & "‘ does not match the pattern '" & pattern1 & "'"
End If

End Sub

Here is the output for various input text values. Please try copying and pasting these input values to understand the working of this “?” wildcard character.

The input text ‘school’ does not match the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOLBOY’ does not match the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOLBBOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOLcBOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOL&BOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOL/BOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOLzBOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOL*BOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘SCHOOL:BOY’ matches the pattern ‘SCHOOL?BOY’

The input text ‘BOY’ does not match the pattern ‘SCHOOL?BOY’

The input text ‘SCOOLBOY’ does not match the pattern ‘SCHOOL?BOY’

Examples of various input text values.

Example Program: The “#” Wildcard Character

In this program we are creating a pattern with a “#”. Now we try to match it with various input expressions. If the input expressions have a digit in the place of “#” and the rest of the word as it is, then the expression is said to match the created pattern. If any of the conditions mentioned above are not met, then we conclude that the input expression does not match the pattern.

Sub wildcard_like_demo()

' declare a string variable and an input variable
Dim pattern1, var_input

' initialize te variable with one "#" character which can accept any single digit in its place to say that it matches this variable / pattern
pattern1 = "GOOD#GIRL"
' literally we have made pattern1 a pattern.

' receive an input from the user and store it in var_input variable
var_input = InputBox("Enter a text. ")

'compare to see if there is any single digit in the place of "#"
If var_input Like pattern1 Then

' if so, the input  matches the pattern
Debug.Print "The input text '" & var_input & "' matches the pattern '" & pattern1 & "'"
Else

' if not, the input does not match the pattern
Debug.Print "The input text '" & var_input & "‘ does not match the pattern '" & pattern1 & "'"
End If

End Sub

Output for Various Input Expressions:

The input text ‘GooGIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘GOOD5GIRL’ matches the pattern ‘GOOD#GIRL’

The input text ‘GOODGIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘GOOD$GIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘GOODGGIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘GOOD~GIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘Good7GIRL’ does not match the pattern ‘GOOD#GIRL’

The input text ‘GOOD8GIRL’ matches the pattern ‘GOOD#GIRL’

Example of output for various input expressions

Example Program: Single Character [] Within Square Brackets 

A single character (as it is) or from a range of characters can be used as a wildcard character within square brackets. In this program we use the range A-Z as the range in the pattern and ensure that any single capital or uppercase letter is used in its place in the input expression.

The expression will match the pattern if: 

  1. Only one since uppercase character is used in the place of [A-Z]
  2. All other characters are as in the pattern, in the same order.
Sub wildcard_like_demo()

' declare a string variable and an input variable
Dim pattern1, var_input

' initialize the variable with [A-Z] in it.
pattern1 = "This is [A-Z] country"
' literally we have made pattern1 a pattern.
  
' receive an input from the user and store it in var_input variable
var_input = InputBox("Enter a text. ")

'compare to see if there is any single character in the place of "[A-Z]"
If var_input Like pattern1 Then

' if so, the input  matches the pattern
    Debug.Print "The input text '" &var_input & "' matches the pattern '" & pattern1 & "'"
Else

' if not, the input does not match the pattern
    Debug.Print "The input text '" & var_input & "‘ does not match the pattern '" & pattern1 & "'"
End If

End Sub

The Output for Various Input Expressions:

The input text ‘INDIA’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is I country’ matches the pattern ‘This is [A-Z] country’

The input text ‘This is MY country’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is a country’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is o country’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is A country’ matches the pattern ‘This is [A-Z] country’

The input text ‘This is 3 country’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is % country’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This is A countr’ does not match the pattern ‘This is [A-Z] country’

The input text ‘This isPcountry’ does not match the pattern ‘This is [A-Z] country’

Example of character within square brackets

Example Program: Single Character Within Brackets (Lowercase) [a-z]

This example is similar to the above one with the difference that lowercase characters are used as a range and the range is not from a-z this time. It is just a subset of it i.e. [b-j]. So, any lowercase letters outside this range will not be considered to match the pattern.

Sub wildcard_like_demo()

' declare a string variable and an input variable
Dim pattern1, var_input

' initialize the variable with [A-Z] in it.
pattern1 = "This is [A-Z] country"
' literally we have made pattern1 a pattern.

' receive an input from the user and store it in var_input variable
var_input = InputBox("Enter a text. ")

'compare to see if there is any single character in the place of "[A-Z]"
If var_input Like pattern1 Then

' if so, the input  matches the pattern
Debug.Print "The input text '" & var_input & "' matches the pattern '" & pattern1 & "'"
Else

' if not, the input does not match the pattern
Debug.Print "The input text '" & var_input & "‘ does not match the pattern '" & pattern1 & "'"
End If

End Sub

Output with Various Input Expressions:

The input text ‘I am [b-j] artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am c artist’ matches the pattern ‘I am [b-j] artist’

The input text ‘I am X artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am y artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am ] artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am % artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am j artist’ matches the pattern ‘I am [b-j] artist’

The input text ‘I am 4] artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am 6 artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am G artist’ does not match the pattern ‘I am [b-j] artist’

The input text ‘I am g artist’ matches the pattern ‘I am [b-j] artist’

Example of lowercase single character within brackets that's a subset of [a-z].

Example Program: Not in Range [!<>]

This program compares and matches each of the input expressions with a pattern that is a wildcard which denotes “not in range.” It is different from the two programs explained above.

An exclamation mark in front of a marked range, but within the same square brackets is said to denote “not in the specified range.”

For example:

[!g-j] should match any single lowercase letter from a to f or from k to z.

Let us again try this with a program as above.

Sub wildcard_like_demo()

' declare a string variable and an input variable
Dim pattern1, var_input

' initialize the variable with [!P-X] in it.
pattern1 = "This is [!P-X] country"
' literally we have made pattern1 a pattern.
  
' receive an input from the user and store it in var_input variable
var_input = InputBox("Enter an expression . ")

'compare to see if there is any single character in the place of "[!P-X] that is within "
If var_input Like pattern1 Then

' if not, the input  matches the pattern
    Debug.Print "The input text '" & var_input & "' matches the pattern '" & pattern1 & "'"
Else

' if so, the input does not match the pattern
    Debug.Print "The input text '" & var_input & "‘ does not match the pattern '" & pattern1 & "'"
End If

End Sub

The Output for Various Input Expressions:

The input text ‘this is my x country’ does not match the pattern ‘This is [!P-X] country’

The input text ‘This is N country’  matches the pattern ‘This is [!P-X] country’

The input text ‘This is Q country’ does not match the pattern ‘This is [!P-X] country’

The input text ‘This is % country’  matches the pattern ‘This is [!P-X] country’

The input text ‘This is 1 country’  matches the pattern ‘This is [!P-X] country’

The input text ‘This is any country’ does not match the pattern ‘This is [!P-X] country’

Conclusion

Several examples of this sort can be given for each wildcard character and a combination of those. But what we try to emphasize here is the use of the “Like“ keyword.  It can be used to compare any expression with a created pattern that may/may not use wildcard characters.

For more information on wildcards and their combination, please look for related articles on our website.

Tagged with: Characters, combinations, Comparison Operators, Excel, Expression, input, Like Operator, Operator, regex, Strings, VBA, VBA For Excel, wildcard characters

The VBA Like operator allows you to compare strings against a pattern. You can search a string to check if it contains another string, or you can check if a string conforms to a certain format.

By searching if a string contains another string, Like does a similar job to the InStr string function, but whereas Like returns a True or False result, InStr returns the position of where one string is in the other.

Pattern Matching

You can use wildcards, character lists and character ranges, in any combination, to create a pattern. The following table illustrates these patterns and what they match.

Pattern Matches Example String Match
? A single character d?g dog True
dig True
drag False
* Zero or more characters d*g dog True
d*g dg True
d*g dragon False
# Any single digit 0 to 9 ### 999 True
### 00 False
[chars] Any single character in the list chars [ab][ab][ab] aba True
[ab][ab][ab] bab True
[ab][ab][ab] cba False
[charchar] Any single character in the range charchar [a-c][d-f][g-i] beh True
[a-c][d-f][g-i] cfg True
[a-c][d-f][g-i] dei False
[!chars] Any single character not in the list chars [!ab][!ab][!ab] ccc True
[!ab][!ab][!ab] abc False
[!charchar] Any single character not in the range charchar [!a-c][!d-f][!g-i] yyz True
[!a-c][!d-f][!g-i] mkb True
[!a-c][!d-f][!g-i] pgi False

Character Ranges

When you use a character range, the characters must appear in ascending sort order e.g. [a-z] not [z-a].

Multiple Ranges

You can specify more than one range for a character position by including them all in the same square brackets e.g. [a-cx-z] would match a, b, c, x, y, z.

Comparison Method

The way Like behaves is dependent on Option Compare.

By default Option Compare is set to Binary, which means the binary representation for a character is used to compare it against another. Effectively this means that pattern matching is case sensitive.

If you want to do case-insensitive comparisons, then at the top of your VBA module you need to have the statement Option Compare Text

IsLike Function

If you look in the sample workbook I created you’ll see I’ve written the function IsLike

VBA Like Function Code

This returns either True or False depending on whether your pattern matches the string. The function can be altered to return something other than True/False of course, if you would find that more useful.

Using Like to Check the Formatting of a String

Not only does Like allow you to match against the contents of the string, it allows you to match the format. For example you might want to check that a phone number has been entered using the correct international format e.g. +Country_Code <Phone Number>

If you wanted to call an Australian land line number you would need to dial +61 x xxxx xxxx. The pattern for this is +61 # #### ####

Download the Workbook

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

Like — оператор VBA для сравнения строки с шаблоном. Нечеткий поиск

Подробности

Категория: Основы VBA

Опубликовано: 17 января 2013

Кроме сравнения строк с использованием операторов «равно», «больше» и «меньше», в языке Visual Basic for Applications (VBA) доступен оператор Like, который можно использовать только для сравнения строк.  

Как программно найти и удалить определенные строки в Excel, используя VBA-оператор Like

http://macros-vba.ru/makrosy/excel/132-kak-najti-stroki-v-excel-poisk-strok-slov-i-simvolov-v-excel

Sub Udalenie_Strok_Po_Shablonu()

    Dim r As Long, FirstRow As Long, LastRow As Long
    Dim Region As Range, iRow As Range, Cell As Range
    Dim Shablon As String
 
    Shablon = "здесь вводится искомый текст"
 
    Set Region = ActiveSheet.UsedRange
    FirstRow = Region.Row
    LastRow = Region.Row - 1 + Region.Rows.Count 
        For r = LastRow To FirstRow Step -1
        Set iRow = Region.Rows(r - FirstRow + 1)
            For Each Cell In iRow.Cells
                If Cell Like Shablon Then
                    Rows(r).Delete
                End If
            Next Cell
        Next r
End Sub

Сравнение строки с шаблоном

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

Специальные символы совпадения с образцом для оператора Like

Образец, с которым должна сравниваться строка, задается при помощи различных специальных символов, представленных в таблице ниже.

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

Если Shablon=»*Круг 2#*», то на листе будут удалены все строки, в которых найдутся слова «Круг 20», «Круг 25» и так далее.

Если Shablon=»S*e», то на листе будут удалены все строки, в ячейках которых будут найдены слова «Sadie», «Salone», «Sophie», «Steve» и так далее.

Если Shablon=»P???y», то удалены будут строки со словами «Penny», «Persy», «Patty» и так далее.

Две последние спецификации символов совпадения из вышеприведенной таблицы используются для указания отдельных символов, совпадение или несовпадение с которыми нужно при поиске. Ниже приведены выражения, использующие квадратные скобки с символьным списком.

Если Shablon=»bi[dg]», то строки со словами в ячейках «bid» и «big» будут удалены, а со словами «bit» и «bin» останутся нетронутыми.

Если же Shablon=»bi[!dg]», то результат будет обратным.

Квадратные скобки можно также использовать для указания диапазона символов, совпадение или несовпадение с которыми необходимо, например Shablon=»ci[a-f]» или Shablon=»ci[!a-f]». В таких случаях диапазоны необходимо указывать от наименьшего до наибольшего символа. Квадратные скобки, в которых ничего не заключено — VBA игнорирует.

Квадратные скобки используются и в тех случаях, когда необходимо сами специальные символы сделать частью шаблона. Например, для того чтобы найти все строки, заканчивающиеся вопросительным знаком, необходимо задать шаблон следующим образом: Shablon=»*[?]».

Для совпадения со знаком дефиса в строке шаблона, дефис помещается в начало или в конец списка символов внутри квадратных скобок. Дефис, помещенный в любое другое место, задает диапазон символов.

Если Shablon=»*g[-]*», то совпадениями будут считаться выражения «big-headed», «plug-ugly», «tag-along» и так далее.

Результат сравнения строк VBA-оператором Like зависит от инструкции Option Compare. При двоичном сравнении оператор различает буквы верхнего и нижнего регистра, а при текстовом — нет.

Другие материалы по теме:

  • MsgBox — оператор VBA для вывода сообщений пользователю процедуры
  • Как удалить скрытые строки? Программное удаление скрытых строк макросом VBA.
  • Как удалить пустые строки? Программное удаление пустых строк макросом VBA
  • Как вставить/добавить новые/пустые строки в Excel?
  • Как удалить строки в Excel по условию? Удаление и скрытие пустых строк и строк, содержащих заданное значение

Понравилась статья? Поделить с друзьями:
  • Word using prefix semi
  • Word vba if не равно
  • Word using prefix mis
  • Word vba if error
  • Word using prefix dis