在VBA Excel中比较具有唯一标识符的列

时间:2018-11-15 14:59:00

标签: excel vba excel-vba

我需要将数据与具有唯一标识符的数据进行比较,该唯一标识符是(A列,“〜” B列)的串联,并将其存储在F列中。在ColumnF中找到所有重复值,以此作为比较的基础到其他列(C列,D列和E列)。例如,

enter image description here

在我的示例中,我有一个重复值5 * 2018〜OPS $ CABUCKLE,在这种情况下,我将使用标识符比较每一列。在我的第一个条目中,列C在第二个条目中具有相同的值222,但是在列D中,第一个条目的值为N,并且在第二个条目中将其更改为Y。 E列中的情况相同。我需要突出显示条目之间发生的更改。

我只在VBA中进行串联,但是我不知道如何找到重复的值并比较另一列?

Sub split1()
    Dim ws As Worksheet, lRow As Long
    Dim x As Long

    Set ws = ThisWorkbook.ActiveSheet
    lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

    With ws
        For x = 1 To lRow
            For Each wrd In .Cells(x, 1)
                d = wrd 
                For Each nm In .Cells(x, 2)
                    .Cells(x, 6).Value = d & "*" & nm
                Next nm
            Next
        Next x
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

这可以满足您的需求,让我知道是否遗漏任何东西

别忘了转到“工具”>“引用”并选中“ Microsoft脚本运行时”

Sub highlight()

    ' need to include Microsoft Scripting Runtime in Tools > References
    Dim prevIDs As Scripting.Dictionary: Set prevIDs = New Scripting.Dictionary
    Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet
    Dim lastRow As Long
    Dim oldRow As Long
    Dim row As Long
    Dim id As String

    With ws
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).row
        For row = 2 To lastRow
            ' set lookup value
            .Cells(row, "F").Value = Trim(CStr(.Cells(row, "A").Value)) & "~" & Trim(CStr(.Cells(row, "B").Value))
            id = .Cells(row, "F").Value
            If prevIDs.Exists(id) Then
                ' get previously found row
                oldRow = prevIDs(id)
                If .Cells(row, "C").Value = .Cells(oldRow, "C").Value Then
                    ' only checks if col D doesn't match --  can change to check both
                    If .Cells(row, "D").Value <> .Cells(oldRow, "D").Value Then
                        .Range("D" & row & ":E" & row).Interior.Color = RGB(100, 200, 100)
                        .Range("D" & oldRow & ":E" & oldRow).Interior.Color = RGB(100, 200, 100)
                    End If
                End If
                ' reset last found row
                prevIDs(id) = row
            Else
                prevIDs.Add id, row
            End If
        Next
    End With
End Sub

这是我的考试:

enter image description here