如何使用vba比较不同工作簿中的一列

时间:2017-03-05 14:38:30

标签: excel vba excel-vba

我想比较不同工作簿中的列。工作簿1中的列位于范围C3中,而工作簿2中的列位于范围L3中。它们之间的数据采用相同的排列方式。我要比较的栏目是关于预订号码。比较列之后,如果所有数据都匹配,那么结果就是msgbox会弹出并说“它全部匹配”,但如果没有,msgbox将提供有关哪个单元格不匹配的信息。

该列的示例是

BOOKING NO
631609
631098
631099
629487
629488

对于通常使用此类型的范围

(Range("C3"), Range("C3").End(xlDown))

有人会帮助我,因为我在excel中使用vba非常初学

1 个答案:

答案 0 :(得分:0)

你可以用这个

Option Explicit

Sub CompareBooking()
    Dim rng1 As Range, rng2 As Range
    Dim iRow As Long
    Dim diffs As String

    With Workbooks("Booking1Wb").Worksheets("booking1") '<--| change "Booking1Wb" and "booking1" to, respectively, your actual workbook and its worksheet names where to find booking numbers from C3 downwards
        Set rng1 = .Range("C3", .Cells(.Rows.count, "C").End(xlUp)) '<--| change "Booking2Wb" and "booking2" to, respectively, your actual workbook and its worksheet names where to find booking numbers from L3 downwards
    End With

    With Workbooks("Booking2Wb").Worksheets("booking2")
        Set rng2 = .Range("L3", .Cells(.Rows.count, "L").End(xlUp))
    End With

    For iRow = 1 To WorksheetFunction.Max(rng1.Rows.count, rng2.Rows.count)
        If rng1(iRow) <> rng2(iRow) Then diffs = diffs & iRow & vbLf
    Next

    If diffs <> "" Then
        MsgBox "Different booking numbers in rows:" & vbCrLf & vbCrLf & diffs
    Else
        MsgBox "All bookings match"
    End If
End Sub