在Excel中使用VBA - 如何突出显示/拉出两个单元格之间的差异

问题描述 投票:1回答:3

我需要比较这两个值,并希望突出显示差异,如果有的话。

下面的片段说的是相同与否,但随之而来的是我需要高亮显示值。

单元格包含字符串值列表。

有人可以帮忙

Public Sub Overview_LRF()

    If (Range("L2").Value = Range("L5").Value) Then

        Gazellevalidation2.OverviewProjects.Value = "Equals"

    Else
        Gazellevalidation2.OverviewProjects.Value = "Not Equals"

    End If
End Sub
excel vba excel-vba
3个回答
2
投票
Sub HighlightDuplicateValues()

    Dim myRange As Range
    Dim myCell As Range

    Set myRange = Selection

    For Each myCell In myRange
        If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then
            myCell.Interior.ColorIndex = 36
        End If
    Next myCell

End Sub

0
投票

请参阅以下示例:

Option Explicit

Sub main()

    Dim in1 As Range
    Dim in2 As Range
    Dim out As Range
    Dim i As Long
    Dim iLen As Long

    Set in1 = Cells(1, 1)
    Set in2 = Cells(1, 2)
    Set out = Cells(1, 3)

    If in1.Value2 = in2.Value2 Then
        out = "<identical>"
    Else
        out.Value2 = vbNullString
        iLen = Len(in1.Value2)
        For i = 1 To iLen        ' find the 1st mismatch
            If in1.Characters(i, 1).Text <> in2.Characters(i, 1).Text Then Exit For
        Next i
        If i <= iLen Then
            out.Value2 = in1.Value2
        Else
            out.Value2 = in2.Value2
            iLen = Len(in2.Value2)
        End If
        out.Characters(i, iLen - i + 1).Font.Color = vbRed
            ' you can make it more robust here
            ' handling nullstring output or space char
    End If

End Sub

如果需要更复杂的比较,可以考虑使用Fuzzy Lookup Add-In for Excel。


0
投票

在同一行上,通过逐个字符检查,制作一个宏来查找两个单元格中的差异。有时候会发生这种情况,我们需要通过角色找出差异。

  • 将数据粘贴到相邻列中,例如col A,Col B.
  • Col A和B中的数据与A1 =“David”,B1 =“Davi1d”相同,但有所不同。
  • 选择第一列并运行宏
  • 宏将检查单元格和相邻单元格并突出显示差异。

Sub ChkDiff()
    i = ActiveSheet.Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row
    Set myRange = Selection
    For Each Cell In myRange
        L1 = Len(Cell.Value)
        L2 = Len(Cell.Offset(0, 1).Value)
        If L1 > L2 Then
            LENT = L1
        Else
            LENT = L2
        End If
        'Cells(j, ActiveCell.Column).Select
        For x = 1 To LENT
            v1 = Cell.Characters(1, x).Text
            v2 = Cell.Offset(0, 1).Characters(1, x).Text
            If v1 <> v2 Then
                Cell.Characters(x, 1).Font.Color = VBA.RGB(255, 0, 0)
            End If
        Next x
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.