比较两张纸之间的列的唯一数据

时间:2016-02-16 04:46:03

标签: vba excel-vba excel

我想在两张纸之间比较A列的唯一数据。

如果数据不匹配,则删除Sheet2中的单元格值。

有人可以帮忙吗?

Sheet1
  A     B   C   D
a1ab1   a1  a   b1
a2ab2   a2  a   b2
a3ab3   a3  a   b3

Sheet2 
  A     B   C   D
a1ab1   a1  a   b1
a2ab2   a2  a   b2
        a5  a   b5
        a6  a   b6
        a7  a   b7
a3ab3   a3  a   b3
a4ab4   a4  a   b4
         a8 a   b8
         a9 a   b9
        a10 a   b10


Sub compare()
    Dim names As Long, values As Long, i, j As Long

    names = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    values = Worksheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Row

    For j = 2 To names
        For i = 2 To values
            If Sheets("Sheet3").Cells(i, 1).value <> Sheets("Sheet1").Cells(j, 1).value Then
            Worksheets("Sheet3").Cells(i, 1).value = "New"
            End If
        Next i
    Next j
End Sub

1 个答案:

答案 0 :(得分:0)

我假设你不想要“新”空白值? 我将使用Find并遍历Sheet3上的值。我试着将我的脚本设置为类似于你编写它的方式。希望它有意义。

Sub Compare()
    Dim names As Range, values As Long, j As Long

    With Worksheets("Sheet1")
        Set names = .Range("A2", .Range("A" & Rows.Count).End(xlUp))
    End With
    values = Worksheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Row

    With Worksheets("Sheet3")
        For j = 2 To values
            If names.Find(What:=.Range("A" & j).Value, _
                          LookIn:=xlValues, _
                          LookAt:=xlWhole) Is Nothing _
            And .Range("A" & j).Value <> "" _
            Then .Range("A" & j).Value = "NEW"
        Next j
    End With
End Sub