Hoppa till huvudinnehåll

Hur jämför jag två strängar för likhet eller markerar skillnader i Excel?

I vissa fall kan du bara behöva jämföra två intilliggande strängceller och markera deras likheter eller skillnader i Excel. Den här artikeln innehåller två metoder för att uppnå det.

Jämför två strängar med formeln
Jämför två strängar för likhet eller markera skillnader med VBA-kod


Jämför två strängar med formeln

Som nedanstående skärmdump visas, om du bara vill veta om de jämförda strängarna matchas eller inte, kan du använda följande formel.

1. Välj en tom cell C2, ange formel = EXAKT (A2, B2) in i formelfältet och tryck sedan på Enter. Se skärmdump:

Anmärkningar: I formeln är A2 och B2 cellerna som innehåller de jämförande strängarna.

2. Fortsätt att välja resultatcellen och dra sedan Fill Handle till cellerna tills du får alla jämförda resultat.

FALSE-resultatet betyder att de jämförda strängarna är olika, och det Sanna resultatet indikerar att de två jämförda strängarna matchas. Se skärmdump:


Jämför två strängar för likhet eller markera skillnader med VBA-kod

Om du vill jämföra två strängar och markera likheterna eller skillnaderna mellan dem. Följande VBA-kod kan hjälpa dig.

1. Tryck andra + F11 samtidigt för att öppna Microsoft Visual Basic för applikationer fönster.

2. I Microsoft Visual Basic för applikationer fönstret klickar Insert > Modulerna. Kopiera och klistra sedan in följande kod i kodfönstret.

VBA-kod: Jämför två kolumnsträngar för likhet eller markera skillnader

Sub highlight()
    Dim xRg1 As Range
    Dim xRg2 As Range
    Dim xTxt As String
    Dim xCell1 As Range
    Dim xCell2 As Range
    Dim I As Long
    Dim J As Integer
    Dim xLen As Integer
    Dim xDiffs As Boolean
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:
    Set xRg1 = Application.InputBox("Range A:", "Kutools for Excel", xTxt, , , , , 8)
    If xRg1 Is Nothing Then Exit Sub
    If xRg1.Columns.Count > 1 Or xRg1.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lOne
    End If
lTwo:
    Set xRg2 = Application.InputBox("Range B:", "Kutools for Excel", "", , , , , 8)
    If xRg2 Is Nothing Then Exit Sub
    If xRg2.Columns.Count > 1 Or xRg2.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lTwo
    End If
    If xRg1.CountLarge <> xRg2.CountLarge Then
       MsgBox "Two selected ranges must have the same numbers of cells ", vbInformation, "Kutools for Excel"
       GoTo lTwo
    End If
    xDiffs = (MsgBox("Click Yes to highlight similarities, click No to highlight differences ", vbYesNo + vbQuestion, "Kutools for Excel") = vbNo)
    Application.ScreenUpdating = False
    xRg2.Font.ColorIndex = xlAutomatic
    For I = 1 To xRg1.Count
        Set xCell1 = xRg1.Cells(I)
        Set xCell2 = xRg2.Cells(I)
        If xCell1.Value2 = xCell2.Value2 Then
            If Not xDiffs Then xCell2.Font.Color = vbRed
        Else
            xLen = Len(xCell1.Value2)
            For J = 1 To xLen
                If Not xCell1.Characters(J, 1).Text = xCell2.Characters(J, 1).Text Then Exit For
            Next J
            If Not xDiffs Then
                If J <= Len(xCell2.Value2) And J > 1 Then
                    xCell2.Characters(1, J - 1).Font.Color = vbRed
                End If
            Else
                If J <= Len(xCell2.Value2) Then
                    xCell2.Characters(J, Len(xCell2.Value2) - J + 1).Font.Color = vbRed
                End If
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub

3. tryck på F5 för att köra koden. I den första Kutools för Excel Välj den första kolumnen med textsträngar du behöver jämföra och klicka sedan på OK knapp.

4. Sedan den andra Kutools för Excel dialogrutan dyker upp, välj de andra kolumnsträngarna och klicka på OK knapp.

5. I det sista Kutools för Excel dialogrutan, om du vill jämföra strängar för likhet, klicka på Ja knapp. Och för att markera skillnaderna i de jämförda strängarna, klicka på Nej knapp. Se skärmdump:

Då kan du se de jämförda resultaten som visas nedan.


Relaterade artiklar:

Bästa kontorsproduktivitetsverktyg

🤖 Kutools AI Aide: Revolutionera dataanalys baserat på: Intelligent utförande   |  Generera kod  |  Skapa anpassade formler  |  Analysera data och generera diagram  |  Anropa Kutools funktioner.
Populära funktioner: Hitta, markera eller identifiera dubbletter   |  Ta bort tomma rader   |  Kombinera kolumner eller celler utan att förlora data   |   Rund utan formel ...
Superuppslag: Flera kriterier VLookup    VLookup med flera värden  |   VSök över flera ark   |   Fuzzy Lookup ....
Avancerad rullgardinslista: Skapa snabbt en rullgardinslista   |  Beroende rullgardinslista   |  Flervals-rullgardinslista ....
Kolumnhanterare: Lägg till ett specifikt antal kolumner  |  Flytta kolumner  |  Växla synlighetsstatus för dolda kolumner  |  Jämför intervall och kolumner ...
Utvalda funktioner: Rutnätsfokus   |  Designvy   |   Stor formelbar    Arbetsbok & Bladhanterare   |  Resursbibliotek (Automatisk text)   |  Datumväljare   |  Kombinera arbetsblad   |  Kryptera/Dekryptera celler    Skicka e-postmeddelanden efter lista   |  Superfilter   |   Specialfilter (filtrera fet/kursiv/genomstruken...) ...
Topp 15 verktygssatser12 text verktyg (lägga till text, Ta bort tecken, ...)   |   50+ Diagram Typer (Gantt Chart, ...)   |   40+ Praktiskt Formler (Beräkna ålder baserat på födelsedag, ...)   |   19 Införande verktyg (Infoga QR-kod, Infoga bild från sökväg, ...)   |   12 Konvertering verktyg (Siffror till ord, Valutaväxling, ...)   |   7 Slå ihop och dela verktyg (Avancerade kombinera rader, Dela celler, ...)   |   ... och mer

Uppgradera dina Excel-färdigheter med Kutools för Excel och upplev effektivitet som aldrig förr. Kutools för Excel erbjuder över 300 avancerade funktioner för att öka produktiviteten och spara tid.  Klicka här för att få den funktion du behöver mest...

Beskrivning


Fliken Office ger ett flikgränssnitt till Office och gör ditt arbete mycket enklare

  • Aktivera flikredigering och läsning i Word, Excel, PowerPoint, Publisher, Access, Visio och Project.
  • Öppna och skapa flera dokument i nya flikar i samma fönster, snarare än i nya fönster.
  • Ökar din produktivitet med 50 % och minskar hundratals musklick för dig varje dag!
Comments (21)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Is there an idiot's guide to Kutools anywhere?
This comment was minimized by the moderator on the site
Hi Sandy,

You can find the guide for each Kutools feature on this page: Kutools for Excel All Features Tutorial
This comment was minimized by the moderator on the site
Hi,
How can i edit the code such that it will compare 2 columns and highlight the differences in both columns?
Eg:
Column 1
A1,A2,A3,A4: Highlight A1 & A3
Column 2
A2,A4,A5,A6,A7: Highlight A5,A6,A7
This comment was minimized by the moderator on the site
Hi Lala,
It would be nice if you could upload a screenshot of your data and the result you want to get.
This comment was minimized by the moderator on the site
Confrontando la cella VIA ROMA 1 con la cella VIA RROMA 1 il programma evidenzia in rosso sia RROMA che 1. Non si può fare in modo che evidenzi solo la lettera diversa e quindi R? Grazie
This comment was minimized by the moderator on the site
in your example, words "lets try" is similar but your code can't highlight it.
This comment was minimized by the moderator on the site
To avoid any trouble of this code with the spaces which should be in ASCII value 32 or 160 (especially if the string comes from HTML) you need to include the test line 46 in a if endif loop as below:
If Not ((Asc(xCell1.Characters(J, 1).Text) = 32 Or Asc(xCell1.Characters(J, 1).Text) = 160) And (Asc(xCell2.Characters(J, 1).Text) = 32 Or Asc(xCell2.Characters(J, 1).Text) = 160)) Then
( line 46 If Not xCell1.Characters(J, 1).Text = xCell2.Characters(J, 1).Text Then Exit For)
End If

Nevertheless thanks for the code.
This comment was minimized by the moderator on the site
How do I add this properly? I am getting an error when I tried to replace line 46. Thank you
This comment was minimized by the moderator on the site
THANK YOU! this is just what i needed!
This comment was minimized by the moderator on the site
I was so hoping this would work. It appears to compare whole cells and not characters within the cells. Simply comparing Candy in one cell to Andy in another finds no similarities. And when I compare for differences the entire name Andy is highlighted in red.
This comment was minimized by the moderator on the site
First off..THANKS Extend Office folks for the good code!!

Try this modification. It simply expands the per character checking loop to include the font color formatting, adds a default "Black", and also compares characters out to the longest of the two cells being compared.

Sub highlight()
    Dim xRg1 As Range
    Dim xRg2 As Range
    Dim xTxt As String
    Dim xCell1 As Range
    Dim xCell2 As Range
    Dim I As Long
    Dim J As Integer
    Dim xLen As Integer
    Dim xDiffs As Boolean
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:
    Set xRg1 = Application.InputBox("Range A:", "Kutools for Excel", xTxt, , , , , 8)
    If xRg1 Is Nothing Then Exit Sub
    If xRg1.Columns.Count > 1 Or xRg1.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lOne
    End If
lTwo:
    Set xRg2 = Application.InputBox("Range B:", "Kutools for Excel", "", , , , , 8)
    If xRg2 Is Nothing Then Exit Sub
    If xRg2.Columns.Count > 1 Or xRg2.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lTwo
    End If
    If xRg1.CountLarge <> xRg2.CountLarge Then
       MsgBox "Two selected ranges must have the same numbers of cells ", vbInformation, "Kutools for Excel"
       GoTo lTwo
    End If
    xDiffs = (MsgBox("Click Yes to highlight similarities, click No to highlight differences ", vbYesNo + vbQuestion, "Kutools for Excel") = vbNo)
    Application.ScreenUpdating = False
    xRg2.Font.ColorIndex = xlAutomatic
    For I = 1 To xRg1.Count
        Set xCell1 = xRg1.Cells(I)
        Set xCell2 = xRg2.Cells(I)
        If xCell1.Value2 = xCell2.Value2 Then
            If Not xDiffs Then xCell2.Font.Color = vbRed
        Else
            xLen = Application.WorksheetFunction.Max(Len(xCell1.Value2), Len(xCell2.Value2))
            For J = 1 To xLen
                xCell2.Characters(J, Len(xCell2.Value2) - J + 1).Font.Color = vbBlack
                If Not xCell1.Characters(J, 1).Text = xCell2.Characters(J, 1).Text Then
                    If Not xDiffs Then
                        If J <= Len(xCell2.Value2) And J > 1 Then
                            xCell2.Characters(1, J - 1).Font.Color = vbRed
                        End If
                    Else
                        If J <= Len(xCell2.Value2) Then
                            xCell2.Characters(J, Len(xCell2.Value2) - J + 1).Font.Color = vbRed
                        End If
                    End If
                End If
            Next J
        End If
    Next
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
just want to say thanks!
This comment was minimized by the moderator on the site
How can I get difference number between two strings?

Example: "123456" and "213456" ==> 2 difference
This comment was minimized by the moderator on the site
Very useful script! thanks
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations