Операторы сравнения чисел и строк, ссылок на объекты (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 вы можете ознакомиться в статье Знаки подстановки для шаблонов.
Return to VBA Code Examples
In VBA, you can compare two strings using the StrComp function. In this tutorial, you will learn how to use this function with different comparison methods.
If you want to learn how to use VBA like operator to compare inexact matches, click here: VBA Like Operator.
If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More
Using the StrComp Function to Compare Two Strings
The StrComp function takes two strings and comparison method as arguments. There are 3 methods of comparison:
- vbBinaryCompare – compares two strings binary (case-sensitive);
- vbTextCompare – compares two strings as texts (case-insensitive);
- vbDatabaseCompare – this method is available only in Microsoft Access and not in VBA.
By default, the function uses the binary method. If we omit this argument, the function will be case-sensitive.
The function returns the following results:
- 0 – if strings are equal;
- -1 – if string 1 is less than string 2;
- 1 – if string 1 is greater than string 2;
- Null – if one of the strings is empty.
Here is the example code:
Dim intResult As Integer
intResult = StrComp("Computer", "Computer")
In this example, we want to check if strings “Computer” and “Computer” are equal, using the default comparison method (binary). The result of the function is in the intResult variable. As you can see in Image, both strings are equal, therefore the intResult has value 0.
Image 1. Using the StrComp function with the binary method in VBA
Using the StrComp Function with Binary and Textual Method
You will now see the difference between using the binary and textual method. The binary method has a binary number for each character, so the uppercase and lowercase are different characters in this method. On the other side, the textual method considers “S” and “s” as the same letters. If you want to make the function case-insensitive, you need to set the third argument to vbBinaryCompare. Here is the code:
Dim intResult1 As Integer
Dim intResult2 As Integer
intResult1 = StrComp("Computer", "CompuTer")
intResult2 = StrComp("Computer", "CompuTer", vbTextCompare)
We want to compare strings “Computer” and “CompuTer”, using both methods.
In the variable intResult1, we will get the value with the binary method, while the intResult2 will get the value with the textual method. You can see the values of these two variables:
Image 2. Using the StrComp function with binary and textual method
The value of intResult1 is 1, which means that two strings are different for the binary method. For the textual method, these two strings are equal, so the value of intResult2 is 0.
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!
Excel VBA String Compare
In our day to day life, we often do comparisons. Comparisons between two people, comparison between two products, comparison between two numbers and for that sake, comparison between two strings as well. While, for comparing two numbers, we have different mathematical functions available such as equality operator, we are in this lecture about to have a look at how to compare strings in under VBA in Excel. The conventional equality operator provides either TRUE or FALSE as a result of a comparison between two numbers or texts. Under VBA, we have STRCOMP as a function that specifies the comparison between two strings. However, the results are not as same as the equality operator (TRUE/FALSE) instead we have three possible results, based on the comparison. We will go through this in detail in the next session of this article. Let’s see the syntax and working of the VBA STRCOMP function.
Syntax of VBA StrComp function:
Where,
String1 and String2 are the two string values we wanted to compare with each other.
How to Compare Strings in VBA?
VbCompareMethod is a method of comparison for the two strings provided. There are three types of comparison mentioned below:
- vbBinaryCompare: Compares two strings binarily and is case sensitive (‘UPPER’ does not equal to ‘upper’). This is the default comparison method if not specified.
- vbTextCompare: Compares two strings as texts and is not case sensitive (‘Upper’ equals to ‘upper’).
- vbDatabaseCompare: Compares the text through the database and is only available for Microsoft Access not under VBA.
This function can return three possible results as follows:
- 0 – If String1 matches with String2.
- 1 – If String1 does not match with String2 and in binary comparison case String1 is lesser than String2.
- -1 – If String 1 does not match with String 2 and in binary comparison case, String 1 is greater than String2.
Examples of String Comparison in VBA
Below are the examples of Excel VBA String Comparison:
You can download this VBA String Comparison — Excel Template here – VBA String Comparison — Excel Template
VBA String Comparison – Example #1
Let’s see some examples of the VBA StrComp function. For this, follow the below steps:
Step 1: Open a new Excel file and hit Alt + F11 to navigate towards the Visual Basic Editor. You can navigate to the Developers tab and click on the Visual Basic button to achieve the same result.
Step 2: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 3: Define a new sub-procedure using the Sub-End clause that can hold your macro.
Code:
Sub Strcomp_Ex1() End Sub
Step 4: Define two new variables String1 and String2 with data type as a string that can be used to store the string values, we wanted to compare with each other.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String End Sub
Step 5: Assign text values to the two variables we have created using the assignment operator. I will assign values as ‘welcome to vba!’ and “WELCOME TO VBA!” respectively to the two variables.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String String1 = "welcome to vba!" String2 = "WELCOME TO VBA!" End Sub
Step 6: Now, define a new variable named CompResult as a string. This variable will be used to store the result of the StrComp function which compares whether two of the strings are equal or not.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String String1 = "welcome to vba!" String2 = "WELCOME TO VBA!" Dim CompResult As String End Sub
Step 7: Now, use the assignment operator to assign the value of StrComp function to this newly defined variable.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String String1 = "welcome to vba!" String2 = "WELCOME TO VBA!" Dim CompResult As String CompResult = StrComp( End Sub
Step 8: Provide the arguments this function statement requires. Use String1 as the first argument String2 variable as the second argument and use vbTextCompare as the comparison argument to this statement.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String String1 = "welcome to vba!" String2 = "WELCOME TO VBA!" Dim CompResult As String CompResult = StrComp(String1, String2, vbTextCompare) End Sub
Step 9: Use VBA MsgBox property to display the output of the StrComp statement which is stored under CompResult variable.
Code:
Sub Strcomp_Ex1() Dim String1 As String Dim String2 As String String1 = "welcome to vba!" String2 = "WELCOME TO VBA!" Dim CompResult As String CompResult = StrComp(String1, String2, vbTextCompare) MsgBox CompResult End Sub
Step 10: Run this code by hitting F5 or Run button placed at the uppermost ribbon of Visual Basic Editor.
Zero here in message box means that two texts we have stored under String1 and String2 are matching with each other though there is a case difference. This is because we have specified vbTextCompare as a comparison argument. This argument checks whether the texts are matching with each other or not irrespective of checking the cases.
VBA String Comparison – Example #2
Now, follow the below steps to compare strings in VBA.
Step 1: Define sub-procedure which can hold your macro.
Code:
Sub strcomp_Ex2() End Sub
Step 2: Define a variable Result as String so that we can assign a value of StrComp function to it.
Code:
Sub strcomp_Ex2() Dim Result As String End Sub
Step 3: Now use the Assignment operator to assign the value of StrComp to the variable named Result.
Code:
Sub strcomp_Ex2() Dim Result As String Result = StrComp( End Sub
Step 4: Now, we need to specify the arguments for this function. Use “india” as a String1, “INDIA” as String2 arguments.
Code:
Sub strcomp_Ex2() Dim Result As String Result = StrComp("india", "INDIA" End Sub
Step 5: For comparison of two strings, use vbBinaryCompare as an argument. It is OK if you put is as blank because it is an optional argument and has a default value as vbBinaryCompare itself. Due to this comparison operation, the system checks the binary codes of two strings given as input (which apparently will be different for two strings provided).
Code:
Sub strcomp_Ex2() Dim Result As String Result = StrComp("india", "INDIA", End Sub
Step 6: Use VBA MsgBox Property to display the Result in the Message box.
Code:
Sub strcomp_Ex2() Dim Result As String Result = StrComp("india", "INDIA", vbBinaryCompare) MsgBox Result End Sub
Step 7: Run this code by hitting F5 or Run button that is placed at the upper ribbon in Visual Basic Editor.
As soon as you run this code, you’ll see an output as “1” in the message box which means these two texts are not equal. Rightly so because of the use of vbBinaryCompare property. This is how we can compare two strings in VBA using the StrComp function. Let’s close this article with some points to be remembered:
Things to Remember
- Comparison argument is optional and can be skipped as it has a default value as vbBinaryCompare which checks the two strings with their binary codes. It means “UPPER” and “upper” are both different.
- If no string value provided, this function returns a Null value
- We can use this function to compare the email addresses of different clients.
- If the String1 is greater than String2. This happens in the case of Binary Comparison; the output will be -1 in that case.
Recommended Articles
This is a guide to the VBA String Comparison. Here we discuss how to Compare Strings in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA SendKeys
- VBA Name Worksheet
- VBA CInt
- VBA SubString
First question is if you want to compare case sensitive or insensitive — with other words: is "ABC" = "abc"
.
The behavior of the =
-operator is defined by Option Compare
— the default is binary
.
Option Compare text
sub foo1
Debug.print "ABC" = "abc" ' Prints "True"
end sub
Option Compare binary ' <-- This is the default!
sub foo2
Debug.print "ABC" = "abc" ' Prints "False"
end sub
The StrComp
-function gets the same results, but without the need of setting the compare option at the top of the module. Instead, you can give the desired way to compare as parameter:
sub foo3
Debug.Print StrComp("ABC", "abc", vbBinaryCompare) = 0 ' <-- Prints "False"
Debug.Print StrComp("ABC", "abc", vbTextCompare) = 0 ' <-- Prints "True"
end sub
if you have leading or trailing blanks in your strings, you always have to use trim
— that’s the case in any programming language I know.
Using Instr
is a rather bad idea to check if two strings as identical, you can use it for substring search. Note that InStr
(and also its counterpart InstrRev
) are using the option compare
setting:
Option Compare text
sub foo4
Debug.print Instr("ABCDE", "cd") ' Prints "3"
end sub
Option Compare binary
sub foo5
Debug.print Instr("ABCDE", "cd") ' Prints "0"
end sub
We have a built-in function to compare two strings in VBA: “StrComp.” We can read it as “String Comparison.” This function is available only with VBA and not as a Worksheet function. It compares any two strings and returns the results as “Zero (0)” if both strings match. We will get “One (1)” if both supplied strings do not match.
In VBA or Excel, we face plenty of different scenarios. One such scenario is comparing two string values. Of course, we can do these in a regular worksheet multiple ways, but how do you do this in VBA?
Table of contents
- Excel VBA String Comparison
- How to Perform String Comparison in VBA?
- Example #1
- Example #2
- Example #3
- Things to Remember here
- Recommended Articles
- How to Perform String Comparison in VBA?
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 String Comparison (wallstreetmojo.com)
Below is the syntax of the “StrComp” function.
First, two arguments are quite simple.
- For String 1, we need to supply the first value we are comparing.
- For String 2, we need to supply the second value we are comparing.
- [Compare] this is the optional argument of the StrComp function. It is helpful when we want to compare case-sensitive comparisons. For example, in this argument, “Excel” is not equal to “EXCEL” because both these words are case sensitive.
We can supply three values here.
- Zero (0) for “Binary Compare,” i.e., “Excel,” is not equal to “EXCEL.” For case-sensitive comparison, we can supply 0.
- One (1) for “Text Compare,” i.e., “Excel,” is equal to “EXCEL.” It is a non-case-sensitive comparison.
- Two (2) this only for database comparison.
The results of the “StrComp” function do not default TRUE or FALSE but vary. Below are the different results of the “StrComp” function.
- We will get “0” if the supplied strings match.
- We will get “1” if the supplied strings are not matching. In the case of numerical matching, we will get 1 if String 1 is greater than string 2.
- We will get “-1” if the string 1 number is less than the string 2 number.
How to Perform String Comparison in VBA?
You can download this VBA String Comparison Excel Template here – VBA String Comparison Excel Template
Example #1
We will match “Bangalore” against the string “BANGALORE.”
But, first, declare two VBA variablesVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more as the string to store two string values.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String End Sub
For these two variables, store two string values.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" End Sub
Now, declare one more variable to store the result of the “StrComp” function.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String End Sub
For this variable, open the “StrComp” function.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp( End Sub
We have already assigned values through variables for “String1” and “String2,” so enter variable names, respectively.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp(Value1, Value2, End Sub
The last part of the function is “Compare” for this choice “vbTextCompare.”
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbTextCompare) End Sub
Now show the “Final Result” variable in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbTextCompare) MsgBox FinalResult End Sub
Let us run the code and see the result.
Output:
Since the strings “Bangalore” and “BANGALORE” are the same, we got the result as 0, i.e., matching. However, both the values are case-sensitive since we have supplied the argument as “vbTextCompare,” it has ignored the case-sensitive match and matched only values, so both the values are the same, and the result is 0, i.e., TRUE.
Code:
Sub String_Comparison_Example1() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbTextCompare) MsgBox FinalResult End Sub
Example #2
We will change the compare method for the same code from “vbTextCompare” to “vbBinaryCompare.”
Code:
Sub String_Comparison_Example2() Dim Value1 As String Dim Value2 As String Value1 = "Bangalore" Value2 = "BANGALORE" Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbBinaryCompare) MsgBox FinalResult End Sub
Now, run the code and see the result.
Output:
Even though both the strings are the same, we got the result as 1, i.e., not matching because we have applied the compare method as “vbBinaryCompare,” which compares two values as case sensitive.
Example #3
Now, we will see how to compare numerical values. For the same code, we will assign different values.
Code:
Sub String_Comparison_Example3() Dim Value1 As String Dim Value2 As String Value1 = 500 Value2 = 500 Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbBinaryCompare) MsgBox FinalResult End Sub
Both the values are 500. Therefore, we will get 0 as a result because both the values match.
Output:
Now, we will change the Value1 number from 500 to 100.
Code:
Sub String_Comparison_Example3() Dim Value1 As String Dim Value2 As String Value1 = 1000 Value2 = 500 Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbBinaryCompare) MsgBox FinalResult End Sub
Run the code and see the result.
Output:
We know Value1 and Value2 are not the same. But the result is -1 instead of 1 because for numerical comparison, when the String 1 value is greater than String 2, we will get this -1.
Code:
Sub String_Comparison_Example3() Dim Value1 As String Dim Value2 As String Value1 = 1000 Value2 = 500 Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbBinaryCompare) MsgBox FinalResult End Sub
Now, we will reverse the values.
Code:
Sub String_Comparison_Example3() Dim Value1 As String Dim Value2 As String Value1 = 500 Value2 = 1000 Dim FinalResult As String FinalResult = StrComp(Value1, Value2, vbBinaryCompare) MsgBox FinalResult End Sub
Run the code and see the result.
Output:
It is not special. If it does not match, we will get only 1.
Things to Remember here
- [Compare] argument of “StrComp” is optional, but in case of case sensitive match, we can utilize this, and the option is “vbBinaryCompare.”
- The result of numerical values is slightly different if String 1 is greater than string 2, and the result will be -1.
- The results are 0 if matched and 1 if not matched.
Recommended Articles
This article has been a guide to the VBA string comparison. Here, we discuss comparing two string values using the StrComp function in Excel VBA and examples and downloading an Excel template. You may also have a look at other articles related to Excel VBA: –
- Guide to VBA String Functions
- VBA Split String into Array
- VBA SubString Methods
- VBA Text