Операторы сравнения чисел и строк, ссылок на объекты (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 вы можете ознакомиться в статье Знаки подстановки для шаблонов.
This doesn’t solve your problem, but… it may help. I was not able to reproduce this behavior:
Player Class Module:
'Class Module: Player
Public Name As String
Public Position As String
Public WAR As Double
Subroutine:
Sub test()
Dim players As Scripting.Dictionary
Set players = New Scripting.Dictionary
Dim pers As Player
Set pers = New Player
pers.Position = "RP"
players.Add "1", pers
Set pers = New Player
pers.Position = "What"
players.Add "2", pers
Set pers = Nothing
For Each pkey In players.Keys
If Not (players(pkey).Position Like "*P*") Then
Debug.Print players(pkey).Position, "Not a P Player"
Else
Debug.Print players(pkey).Position, "Its a P Player"
End If
Next
End Sub
Results in Immediate Pane:
RP Its a P Player
What Not a P Player
Like I said in the comments, I don’t know why this isn’t working for you, but hopefully seeing this in simplified code may point out some problem with your class implementation, or your dictionary iterations, or your like condition… or something that isn’t obvious in the bit of code you have shared.
-
#1
Hi,
Could anone please help me with the VBA code for a «Not Like» comparison ?
I get an error when I try to use the «Not Like» comparison
Code:
If Range("A" & i).Value Not Like "CLOS*" Then
If I use <> «CLOSED» And <> «CLOSE» And <> «CLOSING» then it all runs OK, however I would prefer to get something similar to a «Not Like» operator to work with a wildcard such as *
Thx & Rgds
moonos
What is the shortcut key for Format Selection?
Ctrl+1 (the number one) will open the Format dialog for whatever is selected.
-
#2
Try
Code:
If Not Range("A" & i).Value Like "CLOS*" Then
-
#3
Try this.
Code:
If Not (Range("A" & I).Value Like "CLOS*") Then
-
#4
Try this.
Code:
If Not (Range("A" & I).Value Like "CLOS*") Then
Why the brackets?
-
#5
Peter
They probably aren’t needed in this case — I think using that kind of syntax dates back for me to when I studied Logic at university.
I also think it’s a good idea to use parentheses to make sure that what your testing is what you want to test.
Then you’ve also got to consider operator precedence in calculations.
Again I don’t know if that would make any difference here but you never know.
I mean Man Utd beat Man City in injury time and Celtic beat Hearts too.
-
#6
Thank you for the replies, code now OK.
Peter
I mean Man Utd beat Man City in injury time.
The Man Utd win was achieved with referee precedence over a chronological constant. Quite what it has to do with «Not Like» is a bit unclear unless you are a Man City supporter and then it is definitely «Not Liked»
Rgds
moonos
In this Article
- Using the And Logical Operator
- Using the Or Logical Operator
- Using the Not Logical Operator
- Using the Xor Logical Operator
- Is Operator
- Like Operator
VBA allows you to use the logical operators And, Or, Not, Xor to compare values. The operators are considered “Boolean”, which means they return True or False as a result.
If you want to learn how to compare strings, 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 And Logical Operator
The And logical operator compares two or more conditions. If all the conditions are true, the operator will return True. If at least one of the conditions is not true, the operator will return False. Here is an example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 5
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA and intB are equal to 5. If this is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set values of intA and intB to 5:
intA = 5
intB = 5
After that, we use the And operator in the If statement to check if the values are equal to 5:
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As both variables are equal to 5, the blnResult returns True:
Image 1. Using the And logical operator in VBA
Using the Or Logical Operator
The Or logical operator compares two or more conditions. If at least one of the conditions is true, it will return True. If none of the conditions are true, the operator will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA is equal to 5. or intB is equal to 10. If any of these conditions is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 2. Using the Or logical operator in VBA
Using the Not Logical Operator
The Not logical operator checks one or more conditions. If the conditions are true, the operator returns False. Otherwise, it returns True. Here is the code for the example:
Dim intA As Integer
Dim blnResult As Boolean
intA = 5
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if the value of intA is not equal to 6. If intA is different than 6, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5:
intA = 5
After that, we use the Not operator in the If statement to check if the value of intA is different than 6:
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 3. Using the Not logical operator in VBA
Using the Xor Logical Operator
The Xor logical operator compares two or more conditions. If exactly one of the conditions is true, it will return True. If none of the conditions are true, or more than one are true, it will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if exactly one of the values (intA or IntB) are equal to 5. If only one condition is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5 and intB is 10, the blnResult returns True:
Image 4. Using the Xor logical operator in VBA
Is Operator
The Is Operator tests if two object variables store the same object.
Let’s look at an example. Here we will assign two worksheets to worksheet objects rng1 and rng2, testing if the two worksheet objects store the same worksheet:
Sub CompareObjects()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
If ws1 Is ws2 Then
MsgBox "Same WS"
Else
MsgBox "Different WSs"
End If
End Sub
Of course the worksheet objects are not the same, so “Different WSs” is returned.
Like Operator
The Like Operator can compare two strings for inexact matches. This example will test if a string starts with “Mr.”
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
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend.
Some helpful links to get more insights about Macros, VBA in Excel :
1. Record Macros in Excel.
2. How to Create a Macro in Excel?
In this article, we are going to discuss various comparison operators in Excel VBA.
Implementation :
In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available.
The Developer Tab can be enabled easily by a two-step process :
- Right-click on any of the existing tabs in the top of the Excel window.
- Now select Customize the Ribbon from the pop-down menu.
- The Excel Options Box, check the box Developer to enable it and click on OK.
- Now, the Developer Tab is visible.
- Now click on the Visual Basic option in the Developer tab and make a new module to write the program.
Developer -> Visual Basic -> Tools -> Macros
Now create a Macro and give any suitable name.
This will open the Editor window where can write the code.
Comparison Operators in Excel:
S.No. | Operators |
Definition |
---|---|---|
1 | <> |
Not equal operator is used to compare two operands. If the two operands are not equal it returns TRUE else it returns FALSE. For example : A=10, B= 20 The condition will be TRUE for A <> B, since A and B are not equal. |
2 | = |
Equal operator is used to compare two operands. If the two operands are equal it returns TRUE else it returns FALSE. For example : A=20, B= 20 The condition will be TRUE for A = B, since A and B are equal. |
3 | > |
Greater than operator checks whether the operand on the left hand side is strictly greater than the operand on RHS. If greater then it returns TRUE else FALSE. For example : A=10, B= 5 The condition will be TRUE for A > B, since A is greater than B. |
4 | < |
Less than operator checks whether the operand on the left hand side is strictly less than the operand on RHS. If greater then it returns TRUE else FALSE. For example : A=10, B= 5 The condition will be FALSE for A < B, since A is greater than B. |
5 | >= |
Greater than equal to operator checks whether the operand on the left hand side is either greater or equal to the operand on RHS. If greater or equal then it returns TRUE else FALSE. For example : A=10, B=10 The condition will be TRUE for A >= B, since A is equal to B. |
6 | <= |
Less than equal to operator checks whether the operand on the left hand side is either lesser or equal to the operand on RHS. If lesser or equal then it returns TRUE else FALSE. For example : A=5, B=10 The condition will be TRUE for A <= B, since A is less than B. |
The comparison operators are mostly used with the If Else Then statement in Excel because comparison operators return TRUE if the condition is met and FALSE if not.
The syntax of If Else in Excel is :
If condition/expression Then Code Block for True Else Code Block for False End If
Let’s take an example where values of A=-1 and B=-5 and see the code in Excel VBA for all the comparison operators.
1. Equal To and Not Equal To
Sub Comparison_Operator_Demo() 'Entering the numbers Dim A As Integer: A = -1 Dim B As Integer: B = -5 'Condition for Equal To If A = B Then MsgBox " A and B are equal" Else MsgBox " A and B are not equal" End If End Sub
In the above code, If the condition becomes FALSE since A and B values are not the same. So the code block inside Else will be executed.
Sub Comparison_Operator_Demo() 'Entering the numbers Dim A As Integer: A = -1 Dim B As Integer: B = -5 'Condition for Not Equal To If A <> B Then MsgBox " True since A and B are not same" Else MsgBox " False since A and B are same" End If End Sub
In the above code If the condition becomes TRUE since A and B are not same. So the code block inside If will be executed.
2. Greater than or Less than operator :
Sub Comparison_Operator_Demo() 'Entering the numbers Dim A As Integer: A = -1 Dim B As Integer: B = -5 'Condition for Greater Than If A > B Then MsgBox " A is greater than B" Else MsgBox " A is not greater than B" End If End Sub
In the above code If the condition becomes TRUE since A is greater than B. So the code block inside If will be executed.
Sub Comparison_Operator_Demo() 'Entering the numbers Dim A As Integer: A = -1 Dim B As Integer: B = -5 'Condition for Less Than If A < B Then MsgBox "True because A is less than B" Else MsgBox "False because A is greater than B" End If End Sub
In the above code If the condition becomes FALSE since A is greater than B. So the code block inside Else will be executed.
Similarly, you can do for Greater than equal to and Less than equal to operators.