Comparing to string in excel

Содержание

  1. Функция StrComp
  2. Синтаксис
  3. Settings
  4. Возвращаемые значения
  5. Пример
  6. См. также
  7. Поддержка и обратная связь
  8. VBA String Comparison
  9. Excel VBA String Comparison
  10. How to Perform String Comparison in VBA?
  11. Example #1
  12. Example #2
  13. Example #3
  14. Things to Remember here
  15. Recommended Articles
  16. How to properly use Excel String Compare function?
  17. Properly use Excel string compare function
  18. #1 How do you compare two strings for similarity in Excel?
  19. #2 Compare two strings with personalized return value
  20. #3 How to compare two strings case insensitive in Excel?
  21. In short, how to perform a perfect Excel String compare

Функция StrComp

Возвращает переменную Variant (Integer), показывающую результат сравнения строк.

Синтаксис

StrComp(string1, string2, [ compare ])

Синтаксис функции StrComp содержит следующие именованные аргументы:

Part Описание
строка1 Обязательно. Любое допустимое строковое выражение.
строка2 Обязательно. Любое допустимое строковое выражение.
compare Необязательно. Задает тип сравнения строк. Если аргументсравнения имеет значение Null, возникает ошибка. Если аргумент сравнение опущен, тип сравнения определяется параметром Option Compare.

Settings

Аргумент compare может принимать следующие значения:

Константа Значение Описание
vbUseCompareOption –1 Выполняет сравнение, используя параметр оператора Option Compare.
vbBinaryCompare 0 Выполняется двоичное сравнение.
vbTextCompare 1 Выполняется текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняется сравнение на основе сведений из базы данных.

Возвращаемые значения

Функция StrComp имеет следующие возвращаемые значения:

Если StrComp возвращает
string1 меньше, чем string2 –1
string1 равна string2 0
string1 больше, чем string2 1
string1 или string2 равна Null Null

Пример

В этом примере функция StrComp используется для возврата результатов сравнения строк. Если третий аргумент равен 1, выполняется текстовое сравнение; Если третий аргумент равен 0 или опущен, выполняется двоичное сравнение.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA String Comparison

Excel VBA String Comparison

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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article 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?

Example #1

We will match “Bangalore” against the string “BANGALORE.”

Code:

For these two variables, store two string values.

Code:

Now, declare one more variable to store the result of the “StrComp” function.

Code:

For this variable, open the “StrComp” function.

Code:

We have already assigned values through variables for “String1” and “String2,” so enter variable names, respectively.

Code:

The last part of the function is “Compare” for this choice “vbTextCompare.

Code:

Code:

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:

Example #2

We will change the compare method for the same code from “vbTextCompare” to “vbBinaryCompare.

Code:

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:

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:

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:

Now, we will reverse the values.

Code:

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: –

Источник

How to properly use Excel String Compare function?

Please enable JavaScript

Properly use Excel string compare function

Using MS Excel as an everyday solution, can make your life much easier. It doesn’t matter where you work, the way that Excel works, it will get you out of trouble, with plenty of useful simple functions to count number of occurrences, find the position of a character in a string, count digits in cell or count characters in cell for example.

But Excel has an interesting feature that is much easier to work with than any other software nowadays. It will let you compare two strings and see if they are similar or different from one another.

#1 How do you compare two strings for similarity in Excel?

If you want to determine if two cells are equal, which is a much easier mathematical version, you will use the EXACT function.

It doesn’t matter if there are numbers or words or phrases. This function will examine the cells for which you want to perform a proper Excel String compare.

All you have to do is to click on the cell you want to get the result. After that, click on the formula tab, which is above the cells. On the formula tab you will write the function you will need to work with.

It’s not necessary to look up for the functions in the function settings. You can learn few of them so the process will be faster.

On that tab you will put the equal sign before any function. So it will be like this:

E.g. Let’s say C1 is ‘watermelon’ and C5 is ‘Watermelon’.

The function to perform the exact Excel string compare will be:

On the cell you chose to get the result, Exact will turn into TRUE or FALSE, depending on what you want to compare.

In our case it will be a FALSE result, because the case is different, and the function EXACT is case sensitive. If you want to compare ‘Green’ and ‘Green’, the software will know that the strings are the same and you will get a TRUE result.

You may have a question — what to do in excel if the strings are equal. Quite often, Excel worksheets contain duplicate records that are duplicated many times. But repetition does not always indicate a data entry error. Sometimes repeated entries with the same values ​​were made intentionally. Then the problem may arise when processing, searching for data or analyzing in such a table.

To make it easier for you to work with such tables, we recommend that you automatically merge the same rows in an Excel table by highlighting them in color. Here’s a simple but working tip.

Either way, you don’t have to worry about the result because the Excel software will always get it right. Just take care you use the function you need for the process that you want to perform, in our case an exact Excel string compare between two cells.

#2 Compare two strings with personalized return value

You can even customize the answers you will get on that cell. Instead of getting TRUE or FLASE, you can get YES or NO. But for that you need an additional function, which is the IF function.

Also, don’t forget to use the quotation marks when you are not using a function or cells numbers.

#3 How to compare two strings case insensitive in Excel?

However, the EXACT function is a case sensitive and it exists a much simple way. Forgetting about this function you can also use the equal sign as a pure function.

It is not hard to compare cells between them without paying attention to lowercase or uppercase. It doesn’t matter if you are writing WaTErmelon or simply watermelon because this MS tool will verify the content of the string and it will get the result right.

In short, how to perform a perfect Excel String compare

Of course, there are many ways to compare two strings in MS Excel. But it does require to know a little bit of coding. And not anybody has time to learn the coding way when using Excel for work. So, in the end, this is a proper way to get a proper result for your needs.

Go even further with MSExcel string operations like count number of occurrences, find the position of a character in a string, count digits in cell, or count characters in cell now that you master the string comparison in your favourite spreadsheet program, MSExcel.

Источник

Consider the following:

    A   B
1  ENG  1
2  ENG  1
3  FRA  0
4  FOO  0

I need a formula to populate the B column with 1 if the A column contains the string ENG, or 0 otherwise.

I’ve tried (in cell B1) =IF(A1=(TEXT(ENG;FALSE));1;0) but then it says #NAME? in the cell. Putting ENG between quotation marks doesn’t help either. What should my formula be like?

asked Apr 25, 2013 at 21:10

Pr0no's user avatar

5

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

Brian Pressler's user avatar

answered Jul 17, 2013 at 15:50

Shah's user avatar

ShahShah

6612 gold badges9 silver badges19 bronze badges

1

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

answered Dec 19, 2014 at 9:55

Duncan Jones's user avatar

Duncan JonesDuncan Jones

66.5k29 gold badges190 silver badges252 bronze badges

By default, Excel is not case-sensitive.  For example, with «APPLE» in  A1, and «apple» in A2, the following formula will return TRUE:

=A1=A2 // returns TRUE

To compare text strings in a case-sensitive way, you can use the EXACT function. The Excel EXACT function compares two text strings, taking into account upper and lower case characters, and returns TRUE if they are the same, and FALSE if not.

If we use EXACT to compare A1 and A2 as above, the result is FALSE:

=EXACT(A1,A2) // returns FALSE

EXACT with IF

You can use this result inside the IF function to display a message or make a conditional calculation. For example, to display the message «Yes» for a match and «No» if not, you can use a formula like this:

=IF(EXACT(A2,A2),"Yes","No")

(Note: This guide on Excel string compare is suitable for all Excel versions including Office 365)

Excel is a very reliable spreadsheet tool. In spite of this, errors can creep in due to human oversight. And some of these errors can make or break your database. 

Let us say, for example, you have a list of blacklisted contacts. Now, somebody from your sales team accidentally mixed up the list with good leads. What do you do now? 

While you can technically check the names one by one, it is practically impossible to compare hundreds of names manually. That’s why we need a fast but reliable way to compare strings in Excel. 

Fortunately, Excel has built-in features and functions that can easily compare strings. In this guide, let us explore them. 

You’ll learn:

  1. Method 1: How to Compare Two Case Insensitive Strings? 
  2. Method 2: How to Compare Two Case Sensitive Strings?
  3. Method 3: How to Compare Two Strings Using VBA? 
  4. Method 4: How to Compare Strings Using Conditional Formatting?
  5. Method 5: How to Compare Strings for Similarity?

Related:

How to Remove Spaces in Excel? 3 Easy Methods

How to Insert Bullet Points in Excel? 5 Easy Methods

How to Set Print Area in Excel? Step-by-Step Guide

Method 1: How to Compare Two Case Insensitive Strings? 

To compare two strings, you can simply use the formula IF(A2=B2, “Equal”, “Error”) and drag it to the rest of the cells, provided you don’t care about the cases. 

Excel string compare using the IF function
Excel string compare using the IF function

If necessary, you can later filter similar strings and delete them. Please note that this “IF” function compares strings, numbers, dates, boolean expressions, etc. 

Method 2: How to Compare Two Case Sensitive Strings?

In case, you want to compare strings while accounting for different upper and lower case versions use the EXACT function. 

Let us see how to do this: 

  1. In a separate column, enter the formula IF(EXACT(D2,E2), “Equal”, “Error”)
  1. This will return “Equal” if the values are exactly the same. Drag the formula to the entire range. 
Case sensitive Excel string compare using IF and EXACT functions
Case sensitive Excel string compare using IF and EXACT functions

Please note that the IF formula is optional and is only used for displaying a message instead of “TRUE” or “FALSE”. 

Also Read:

How to VLOOKUP From Another Sheet?

How to Move Rows in Excel? 5 Easy Methods

How to Fix the Excel Circular Reference Error?

Method 3: How to Compare Two Strings Using VBA? 

Well, the methods discussed above work only if you are comparing simple strings. What if you need to compare complex strings? 

Isn’t there any efficient way to compare strings in Excel? 

Fortunately, we have VBA. Using this VBA code, we can not only compare two strings but also highlight the differences between them. 

Let us see how to do this: 

  1. Open the relevant Excel spreadsheet and press Alt+F11 to go to the VBA editor. 
  1. Here, click on the Module option under Insert 
Click on the Module option under the Insert menu
Click on the Module option under the Insert menu
  1. In the New Module window, paste the following VBA code and run it using the F5 shortcut. 
Sub highlight()
    Dim R1 As Range
    Dim R2 As Range
    Dim Txt As String
    Dim C1 As Range
    Dim C2 As Range
    Dim I As Long
    Dim J As Integer
    Dim xL As Integer
    Dim xD As Boolean
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      Txt = ActiveWindow.RangeSelection.AddressLocal
    Else
      Txt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:
    Set R1 = Application.InputBox("Range A:", "Compare_Strings", Txt, , , , , 8)
    If R1 Is Nothing Then Exit Sub
    If R1.Columns.Count > 1 Or R1.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Compare_Stringsl"
        GoTo lOne
    End If
lTwo:
    Set R2 = Application.InputBox("Range B:", "Compare_Strings", "", , , , , 8)
    If R2 Is Nothing Then Exit Sub
    If R2.Columns.Count > 1 Or R2.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Compare_Strings"
        GoTo lTwo
    End If
    If R1.CountLarge <> R2.CountLarge Then
       MsgBox "Two selected ranges must have the same numbers of cells ", vbInformation, "Compare_Strings"
       GoTo lTwo
    End If
    xD = (MsgBox("Yes to Highlight Common String, No to highlight differences ", vbYesNo + vbQuestion, "Compare_Strings") = vbNo)
    Application.ScreenUpdating = False
    R2.Font.ColorIndex = xlAutomatic
    For I = 1 To R1.Count
        Set C1 = R1.Cells(I)
        Set C2 = R2.Cells(I)
        If C1.Value2 = C2.Value2 Then
            If Not xD Then C2.Font.Color = vbGreen
        Else
            xL = Len(C1.Value2)
            For J = 1 To xL
                If Not C1.Characters(J, 1).Text = C2.Characters(J, 1).Text Then Exit For
            Next J
            If Not xD Then
                If J <= Len(C2.Value2) And J > 1 Then
                    C2.Characters(1, J - 1).Font.Color = vbGreen
                End If
            Else
                If J <= Len(C2.Value2) Then
                    C2.Characters(J, Len(C2.Value2) - J + 1).Font.Color = vbRed
                End If
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub
  1. In the Compare_Strings dialog box, select the ranges of the strings you want to compare and click OK. 
Select Range A
Select Range A
Select Range B
Select Range B
  1. Choose whether to highlight the differences or the similarities between the strings.  All differences will be highlighted in red and all similarities will be highlighted in green. 

Method 4: How to Compare Strings Using Conditional Formatting?

What if you are in a hurry and want to quickly compare strings for duplicates?

Well, you can take the help of the Conditional Formatting feature to instantly compare and highlight duplicates in Excel. 

To do this, just select the range of cells where you want to look for duplicates and go to Conditional Formatting > Highlight Cell Rules > Duplicate Values. This will highlight all duplicates in this range. 

Highlight duplicates using Conditional Formatting
Highlight duplicates using Conditional Formatting
Equal strings will be highlighted in red
Equal strings will be highlighted in red

Method 5: How to Compare Strings for Similarity? 

If you are looking to find similarities between two sets of un-identical strings, you can use this method. 

Just enter the formula IFERROR( IF (SEARCH (text1, text2),if_true),if_false) in an adjacent column and drag it to the entire range. In this example, we are comparing column D with column E. Hence the formula will be =IFERROR(IF(SEARCH(D2,E2),”Similar”),”Different”)

Using IFERROR to find similar strings
Using IFERROR to find similar strings

This will check if text1 is inside text2 or not and return “Similar” or “Different” accordingly. 

Suggested Reads:

How to Extract an Excel Substring? – 6 Best Methods

Excel Quick Analysis Tool – The Best Guide (5 Examples)

How to Lock Cells in Excel?— 4 Best Methods with Examples

Let’s Wrap Up

In this short guide, we discussed five easy methods to compare strings in Excel. Try each one out and use the one which suits you best. In fact, you can modify some of these methods to your liking. Please let me know if you have any questions in the comments section. 

We are always happy to help. 

Please visit our free resources section for more high-quality Excel guides.

Ready to upskill your Excel knowledge? Simon Sez IT has been teaching Excel for over ten years. For a low, monthly fee you can get access to 130+ training courses. Click here for advanced Excel courses with in-depth training modules.

Simon Calder

Chris “Simon” Calder was working as a Project Manager in IT for one of Los Angeles’ most prestigious cultural institutions, LACMA.He taught himself to use Microsoft Project from a giant textbook and hated every moment of it. Online learning was in its infancy then, but he spotted an opportunity and made an online MS Project course — the rest, as they say, is history!

Using MS Excel as an everyday solution, can make your life much easier. It doesn’t matter where you work, the way that Excel works, it will get you out of trouble, with plenty of useful simple functions to count number of occurrences, find the position of a character in a string, count digits in cell or count characters in cell for example.

Using MS Excel as an everyday solution, can make your life much easier. It doesn’t matter where you work, the way that Excel works, it will get you out of trouble, with plenty of useful simple functions to count number of occurrences, find the position of a character in a string,  count digits in cell   or  count characters in cell   for example.

But Excel has an interesting feature that is much easier to work with than any other software nowadays. It will let you compare two strings and see if they are similar or different from one another.

#1 How do you compare two strings for similarity in Excel?

If you want to determine if two cells are equal, which is a much easier mathematical version, you will use the EXACT function.

It doesn’t matter if there are numbers or words or phrases. This function will examine the cells for which you want to perform a proper Excel String compare.

All you have to do is to click on the cell you want to get the result. After that, click on the formula tab, which is above the cells. On the formula tab you will write the function you will need to work with.

It’s not necessary to look up for the functions in the function settings. You can learn few of them so the process will be faster.

On that tab you will put the equal sign before any function. So it will be like this:

Excel String compare case sensitive: =EXACT

E.g. Let’s say C1 is ‘watermelon’ and C5 is ‘Watermelon’.

The function to perform the exact Excel string compare will be:

Exact case sensitive Excel string compare: =EXACT(C1,C5)

On the cell you chose to get the result, Exact will turn into TRUE or FALSE, depending on what you want to compare.

In our case it will be a FALSE result, because the case is different, and the function EXACT is case sensitive. If you want to compare ‘Green’ and ‘Green’, the software will know that the strings are the same and you will get a TRUE result.

You may have a question — what to do in excel if the strings are equal. Quite often, Excel worksheets contain duplicate records that are duplicated many times. But repetition does not always indicate a data entry error. Sometimes repeated entries with the same values ​​were made intentionally. Then the problem may arise when processing, searching for data or analyzing in such a table.

To make it easier for you to work with such tables, we recommend that you automatically merge the same rows in an Excel table by highlighting them in color. Here’s a simple but working tip.

Either way, you don’t have to worry about the result because the Excel software will always get it right. Just take care you use the function you need for the process that you want to perform, in our case an exact Excel string compare between two cells.

#2 Compare two strings with personalized return value

You can even customize the answers you will get on that cell. Instead of getting TRUE or FLASE, you can get YES or NO. But for that you need an additional function, which is the IF function.

Compare two string with custom return value: =IF(EXACT(C1,C5), "YES", "NO" )

Also, don’t forget to use the quotation marks when you are not using a function or cells numbers.

#3 How to compare two strings case insensitive in Excel?

However, the EXACT function is a case sensitive and it exists a much simple way. Forgetting about this function you can also use the equal sign as a pure function.

Excel string compare case insensitive: =C1=C5

It is not hard to compare cells between them without paying attention to lowercase or uppercase. It doesn’t matter if you are writing WaTErmelon or simply watermelon because this MS tool will verify the content of the string and it will get the result right.

In short, how to perform a perfect Excel String compare

Of course, there are many ways to compare two strings in MS Excel. But it does require to know a little bit of coding. And not anybody has time to learn the coding way when using Excel for work. So, in the end, this is a proper way to get a proper result for your needs.

Excel string compare case sensitive: =EXACT(C1,C5)
Excel string compare case insensitive: =C1=C5

Go even further with MSExcel string operations like count number of occurrences, find the position of a character in a string, count digits in cell, or  count characters in cell   now that you master the string comparison in your favourite spreadsheet program, MSExcel.

Complete 2019 Excel for Beginners in video

Понравилась статья? Поделить с друзьями:
  • Compared to some others the word tourist is fairly new first
  • Compare two things word
  • Compare two column in excel
  • Compare to texts in word
  • Compare to documents with word