将sheet1中的每一行与sheet2中的每一行进行比较 - 在​​sheet3中没有写对 - HARD

时间:2014-03-31 07:42:55

标签: vba comparison compare rows

我有一个非常大的Excel文件,它具有完全相同的列但是dirosa。很多行。我需要一个VBA脚本的帮助来比较sheet1中的每个整个Eos和sheet2如果它没有找到一对我想让它在sheet3中写入行。 非常重要的是脚本在sheet1的第1行开始,然后在sheet2中循环true整个范围以检查它是否喜欢一对。如果它找不到匹配,那么我希望它在sheet3中写入该行。

请得到我能得到的所有帮助!!

使用Excel 2010 - VBA脚本请

1 个答案:

答案 0 :(得分:1)

你可以用循环来做。如果列中有很多行,这可能会花费很多时间。否则它工作正常。基本上,代码从sheet1获取每个值,将其与sheet2的每个值进行比较,如果未找到匹配则将其写入sheet3。然后它重复相同的事情,但将sheet2值与sheet1值进行比较。

Sub Compare()

'Get Lengths of the Columns
Z_1 = ActiveWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
Z_2 = ActiveWorkbook.Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
'Variable row index for Sheet3
a = 1

'Find exclusive values in sheet1
For i = 1 To Z_1
    j = 1
    Do Until ActiveWorkbook.Sheets(1).Cells(i, 1) = ActiveWorkbook.Sheets(2).Cells(j, 1) Or j > Z_2
        j = j + 1
    Loop
    If ActiveWorkbook.Sheets(1).Cells(i, 1) <> ActiveWorkbook.Sheets(2).Cells(j, 1) Then
        ActiveWorkbook.Sheets(3).Cells(a, 1) = ActiveWorkbook.Sheets(1).Cells(i, 1)
        a = a + 1
    End If
Next i

'Find exclusive values in sheet2
For i = 1 To Z_2
    j = 1
    Do Until ActiveWorkbook.Sheets(2).Cells(i, 1) = ActiveWorkbook.Sheets(1).Cells(j, 1) Or j > Z_1
        j = j + 1
    Loop
    If ActiveWorkbook.Sheets(2).Cells(i, 1) <> ActiveWorkbook.Sheets(1).Cells(j, 1) Then
         ActiveWorkbook.Sheets(3).Cells(a, 1) = ActiveWorkbook.Sheets(2).Cells(i, 1)
        a = a + 1
    End If
Next i

End Sub