比较同一工作簿中两个excel工作表中的两组列

时间:2015-08-04 16:18:17

标签: excel vba excel-vba

Sheet 1中

+------+-------+
|  ID  | Name  |
+------+-------+
| 1245 | James |
| 9377 | Jacob |
| 6201 | David |
| .    | .     |
| .    | .     |
| .    | .     |
+------+-------+

Sheet 2中

+------+-------+
|  ID  | Name  |
+------+-------+
| 1245 | James |
| 9007 | Adam  |
| 9377 | Jacob |
| 6201 | David |
| .    | .     |
| .    | .     |
| .    | .     |
+------+-------+

理论上,两张纸都是彼此的副本,但Sheet2有额外的数据。 Sheet1包含10000行,Sheet2包含15000.如何在两个工作表之间进行比较以显示/突出显示Sheet2中的5000个不同行?

2 个答案:

答案 0 :(得分:0)

对于这样的任务,我使用adodb记录集来存储第一张纸上的内容。然后我读了第二张纸,看看它是否在第一张纸上。

在VBA IDE中,转到工具菜单并选择参考。选择“Microsoft ActiveX Data Objects 2.8 Library。”

Dim rs As New ADODB.Recordset
Dim ws As Excel.Worksheet
Dim lRow As Long

    Set ws = Application.ActiveSheet

    'Add fields to your recordset for storing data.  You can store sums here.
    With rs
        .Fields.Append "Row", adInteger
        .Fields.Append "ID", adInteger
        .Fields.Append "NAME", adChar, 50
        .Open
    End With

    lRow = 1

    'Loop through and record what is in the first sheet
    Do While lRow <= ws.UsedRange.Rows.count

        rs.AddNew
        rs.Fields("Row").Value = lRow
        rs.Fields("ID").Value = ws.Range("A" & lRow).Value
        rs.Fields("NAME").Value = ws.Range("B" & lRow).Value
        rs.Update

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop

    'Switch to the second worksheet
    Set ws = Nothing
    Set ws = ActiveWorkbook.Sheets("Sheet2")
    ws.Activate

    'Loop through and compare to what was on the first column
    lRow = 1
    Do While lRow <= ws.UsedRange.Rows.count

        rs.Filter = ""
        rs.Filter = "ID=" & ws.Range("A" & lRow).Value
        If rs.RecordCount = 0 Then
             'We don't have a match, color the row
             Rows(lRow).Interior.Color = vbBlue
        End If

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop

答案 1 :(得分:0)

您可以在Sheet2上使用以下功能查找Sheet2的值,看看它们是否存在于Sheet1上:

=IF(COUNTIFS(A2,Sheet1!A:A,B2,Sheet1!B:B)>0,"","X")

这是假设您在C2上的Sheet2中输入公式。 COUNTIFS()只需检查Sheet1ID Name,然后返回找到匹配的行数。如果我们找到它,我们就不在乎("")。如果我们找不到它,那么Sheet2将其排除,我们会用"X"标记。

当然,您也可以在VBA中执行此操作:

With Sheet2.Range("C2:C" & Sheet2.UsedRange.Rows.Count)
    .Formula = "=IF(COUNTIFS(A2,Sheet1!A:A,B2,Sheet1!B:B)>0,"""",""X"")"
    .Value = .Value ' (If you want to remove the formula)
End With