根据第a列和第d列的值比较来自两个工作表的数据

时间:2018-08-22 19:22:21

标签: excel vba

我正在寻找一个vba代码,该代码循环遍历sheet1中的所有行,以基于sheet1中的colmn a和d值在sheet2中的a列和d列中找到匹配的数据来查找数据匹配。示例列a 1011列d john。如果在sheet2的某处,列a = 1011,列d同一行= john,则找到匹配项。我需要将所有不匹配项保存到新工作簿中。

1 个答案:

答案 0 :(得分:0)

尝试一下。将结果放入此工作簿的Sheet3中。 >>

Option Explicit  '  it is your friend

Sub do_FindOrphans()

'   create or find Sheet3, and clear it out
    If Not Evaluate("ISREF('Sheet3'!A1)") Then
        Sheets.Add After:=ActiveSheet
        ActiveSheet.Name = "Sheet3"
    Else
        Sheets("Sheet3").Activate
    End If
    Cells.Select
    Selection.ClearContents

'   initialize max row#, and copy in column headings
    Sheets("Sheet1").Select
    Dim s1row As Long, s1max As Long, s1col As Long, s1endcol As Integer
    s1max = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
    Sheets("Sheet2").Select
    Dim s2row As Long, s2max As Long
    s2max = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
    Dim s3row As Long, matched As String

    With ActiveSheet
        s1endcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
    s3row = 1
    For s1col = 1 To s1endcol
        Sheets("Sheet3").Cells(s3row, s1col) = Sheets("Sheet1").Cells(1, s1col)
    Next s1col

'   step thru sheet1
    For s1row = 2 To s1max
        matched = "N"
'       step thru sheet2
        For s2row = 2 To s2max
'           Compare the keys
            If Sheets("Sheet1").Cells(1, s1row) = Sheets("Sheet2").Cells(1, s2row) _
            And Sheets("Sheet1").Cells(4, s1row) = Sheets("Sheet2").Cells(4, s2row) Then
                matched = "Y"
                Exit For
            End If
        Next s2row
        If matched = "N" Then
            s3row = s3row + 1
            For s1col = 1 To s1endcol
                Sheets("Sheet3").Cells(s3row, s1col) = Sheets("Sheet1").Cells(s1row, s1col)
            Next s1col
        End If
    Next s1row

End Sub