我在两个单元格中有不同文本的文本。我正在尝试识别两个单元格之间的差异(文本之间的区别:添加或缺失的文本)。
示例:
A1:ThisisasystemgeneratedmentanddoesnotrequiresignatureAnyunauthorizedusedisclosuredisseminationoringofthisdocumentisstrictlyprohibitedandmaybeunlawful
B1:Thisisasystemgenerateddocumentanddoesnotrequiresignatureunauthorizedusedisclosuredisseminationorcopyingofthisdocumentisstrictlyprohibitedandmaybeunful
单元格A1
和B1
都应突出显示文字差异。我该如何实现呢?
答案 0 :(得分:0)
这实际上是一个相当棘手的场景,但是你走了:
Public Sub FindDistinctSubstrings()
Dim a$, b$, i&, k&, rA As Range, rB As Range
Set rA = [a1]: a = rA
Set rB = [b1]: b = rB
k = Len(a): If Len(b) > k Then k = Len(b)
Do
i = i + 1
If Mid$(a, i, 1) <> Mid$(b, i, 1) Then
Align i, a, b, rA, rB
End If
DoEvents
Loop Until i > k
k = Len(a): If Len(b) > k Then k = Len(b)
For i = 1 To k
If Mid$(a, i, 1) = "." Then rB.Characters(i, 1).Font.Color = vbRed
If Mid$(b, i, 1) = "." Then rA.Characters(i, 1).Font.Color = vbRed
Next
Do
k = InStr(rA, "."): If k Then rA.Characters(k, 1).Delete
Loop Until k = 0
Do
k = InStr(rB, "."): If k Then rB.Characters(k, 1).Delete
Loop Until k = 0
End Sub
Private Sub Align(k&, a$, b$, rA As Range, rB As Range)
Dim i&, iMax&, nI&, nMaxI&, j&, jMax&, nJ&, nMaxJ&
Const LOOK_AHEAD_BUFFER = 30
For i = 0 To LOOK_AHEAD_BUFFER
nI = CountMatches(Space$(i) & Mid$(a, k, LOOK_AHEAD_BUFFER), Mid$(b, k, LOOK_AHEAD_BUFFER))
If nI > nMaxI Then
nMaxI = nI: iMax = i
End If
Next
For j = 0 To LOOK_AHEAD_BUFFER
nJ = CountMatches(Mid$(a, k, LOOK_AHEAD_BUFFER), Space$(j) & Mid$(b, k, LOOK_AHEAD_BUFFER))
If nJ > nMaxJ Then
nMaxJ = nJ: jMax = j
End If
Next
If nMaxI > nMaxJ Then
a = Left$(a, k - 1) & String$(iMax, ".") & Mid$(a, k)
rA = a: k = k + iMax
Else
b = Left$(b, k - 1) & String$(jMax, ".") & Mid$(b, k)
rB = b: k = k + jMax
End If
End Sub
Private Function CountMatches(a$, b$) As Long
Dim i&, k&, c&
k = Len(a): If Len(b) < k Then k = Len(b)
For i = 1 To k
If Mid$(a, i, 1) = Mid$(b, i, 1) Then c = c + 1
Next
CountMatches = c
End Function