Ir para o conteúdo principal

Como comparar duas strings para semelhança ou destacar diferenças no Excel?

Em alguns casos, você só precisa comparar duas células adjacentes de strings e marcar suas semelhanças ou diferenças no Excel. Este artigo fornece dois métodos para você conseguir isso.

Compare duas strings com fórmula
Compare duas strings para semelhanças ou destaque as diferenças com o código VBA


Compare duas strings com fórmula

Como mostrado na captura de tela abaixo, se você apenas deseja saber se as strings comparadas são correspondidas ou não, você pode aplicar a seguinte fórmula.

1. Selecione uma célula em branco C2, insira a fórmula = EXATO (A2, B2) na Barra de Fórmulas e, em seguida, pressione a tecla Enter. Veja a imagem:

Note: Na fórmula, A2 e B2 são as células que contêm as strings de comparação.

2. Continue selecionando a célula de resultado e arraste o identificador de preenchimento para as células até obter todos os resultados comparados.

O resultado FALSE significa que as strings comparadas são diferentes, e o resultado TRUE indica que as duas strings comparadas são correspondidas. Veja a imagem:


Compare duas strings para semelhanças ou destaque as diferenças com o código VBA

Se você quiser comparar duas strings e destacar as semelhanças ou diferenças entre elas. O seguinte código VBA pode ajudá-lo.

1. Pressione outro + F11 simultaneamente para abrir o Microsoft Visual Basic para Aplicações janela.

2. No Microsoft Visual Basic para Aplicações janela, clique em inserção > Módulo. Em seguida, copie e cole o código a seguir na janela de código.

Código VBA: compare duas strings de coluna para semelhanças ou destaque as diferenças

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. aperte o F5 chave para executar o código. Em primeiro Kutools for Excel caixa de diálogo, selecione a primeira coluna de strings de texto que você precisa comparar e clique no botão OK botão.

4. Então o segundo Kutools for Excel caixa de diálogo aparece, selecione as sequências da segunda coluna e clique no OK botão.

5. No último Kutools for Excel caixa de diálogo, se você deseja comparar strings de semelhança, clique no Sim botão. E para destacar as diferenças das strings comparadas, clique no Não botão. Veja a imagem:

Então você pode ver os resultados comparados conforme a imagem mostrada abaixo.


Artigos relacionados:

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
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