逐字母比较

时间:2015-08-29 09:36:27

标签: excel excel-vba vba

我在两个单元格(A1和B1)中有两组数据,没有任何特殊字符(。,/;:'" - @#$%^& *(){} [] )并且单词之间也没有空格,

问题是我需要比较两个细胞并识别并突出显示差异。

例如:

+
    A1中缺少
  • (A1): howtobuilfmacroincludingthesecrria (B1): howbuilfmacroincludingthesecriteria
  • 和B1 ite缺失

宏应突出显示B1中的to和A1中的ite

2 个答案:

答案 0 :(得分:1)

执行相互检查非常困难,因为excel不知道这些单词。它代表什么? 您可以像这样检查一列:

Sub CompareMacro()
Dim columnA As Integer
Dim columnB As Integer
Dim NumberOfCaracters As Integer
Dim f As Integer
f = 1
For numbuerOfRows = 1 To 5
    columnA = Len(Worksheets(1).Cells(numbuerOfRows, 1))
    columnB = Len(Worksheets(1).Cells(numbuerOfRows, 2))

    If columnA > columnB Then
        NumberOfCharacters = columnA
    Else
        NumberOfCaracters = columnB
    End If

    Dim columnALetters(3) As Variant

    For i = 1 To NumberOfCaracters

        If Mid(Worksheets(1).Cells(numbuerOfRows, 1), i, 1) = Mid(Worksheets(1).Cells(numbuerOfRows, 2), f, 1) Then                 
             f = f + 1
         Else
    Worksheets(1).Cells(numbuerOfRows, 1).Characters(i, 1).Font.Color = vbRed
        End If      
    Next i
Next numbuerOfRows
End Sub

答案 1 :(得分:1)

确保文本字符串位于单元格A1和B1中。

将这些例程放在标准代码模块中(Alt-F11)。

运行FindDistinctSubstrings例程(工作表中的Alt-F8)。

Public Sub FindDistinctSubstrings()
    Dim a$, b$
    a = [a1]
    b = [b1]
    S1inS2 0, 2, a, b, [a1], vbRed
    S1inS2 0, 2, b, a, [b1], vbRed
    S1inS2 1, 3, a, b, [a1], vbBlack
    S1inS2 1, 3, b, a, [b1], vbBlack
End Sub
Private Sub S1inS2(yes&, k&, s1$, s2$, r As Range, color&)
    Dim i&
    For i = 1 To Len(s1)
        If (yes = 0 And 0 = InStr(s2, Mid$(s1, i, k))) Or (yes = 1 And 0 < InStr(s2, Mid$(s1, i, k))) Then
            r.Characters(i, k).Font.color = color
        End If
    Next
End Sub