如何在Excel中比较两个字符串的相似性或突出不同之处
在这篇文章中,我们将学习如何在Excel中比较两个相邻的字符串,以确定差异或相似之处。这篇文章中解释了两种方法,如下所述。
使用一个公式比较两个字符串的相似性。
使用VBA代码比较并突出显示两个字符串的相似性或差异。
使用公式比较两个字符串的相似性
第1步 – 下面是一个示例数据,用来比较两列的字符串。
第2步 – 现在,在 “匹配结果 “栏中输入以下公式,并将其拖到需要进行数据对比的最后一行,然后按回车键。
=EXACT(A2, B2)
注意 – 在该公式中,A2和B2是比较字符串的单元格。
公式语法说明
参数 | 描述 |
---|---|
EXACT(text1, text2) | Text1 这是第一个字符串,需要与另一个字符串进行比较。 Text2 这是第二个字符串,需要与text1进行比较。 |
使用VBA代码比较并突出显示两个字符串的相似或不同之处
第1步 – 从键盘上按下Alt+F11键,Microsoft Visual Basic for Applications窗口将打开。
上述编辑器也可以使用 “开发人员 “选项卡打开,如下图所示
第2步 – 在Microsoft Visual Basic for Applications窗口中,双击项目面板中可用的ThisWorkbook。
第3步 – 现在复制下面的VBA代码并在ThisWorkbook(代码)窗口中输入同样的代码。
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
第4步 – 一旦代码输入完毕,按键盘上的Alt+Q键,关闭Microsoft Visual Basic for Applications窗口。
第5步 – 接下来,将文件保存为:Excel Macro-Enabled Workbook。
第6步 – 现在按Alt+F8来运行该代码。
第7步 – 选择宏的名称并点击运行。
第8步 – 第一个Kutools for Excel对话框将打开。在这里,选择你需要比较的第一列文本字符串,然后点击确定按钮。
第9步 按钮。
第10步 – 之后,一个新的Kutools for Excel对话框打开。在这里,如果你想比较字符串的相似性,那么就点击 “是”,如果你想突出字符串的差异,就点击下面截图中的 “否”。
第11步 – 如果选择 “是”,类似的字符串将被突出显示,如下所示。
第12步 – 如果选择 “否”,不同的字符串将被突出显示,如下所示。
结论
因此,我们已经学会了两种方法来识别Excel数据中不同和相似的字符串。请注意,VBA代码只限于识别一些特殊字符。例如,它不能比较含有撇号和感叹号的字符串。