匹配数据不同的工作簿和不同的顺序

时间:2017-03-07 08:14:17

标签: excel vba excel-vba

我尝试匹配来自2个不同工作表和2个不同工作簿的名称数据。我已经创建了宏vba。但是当数据处于相同的顺序时,这个宏是针对数据类型的,如果数据不是以相同的顺序怎么样?

名称数据的示例

In first workbook

Name
Andre
Renata
Marie

In second workbook

Name
Andre
Marie
Renata

使用我的宏,上面数据的结果不匹配。但我希望以上数据的结果是MATCH。

这是我的宏vba

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

        With Workbooks("A.xls").Worksheets("1")
        Set rng1 = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
    End With

    With Workbooks("B.xlsx").Worksheets("1")
        Set rng2 = .Range("M3", .Cells(.Rows.Count, "M").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 name in rows:" & vbCrLf & vbCrLf & diffs
    Else
        MsgBox "All names match"
    End If

如果你知道怎么做,请帮助我

1 个答案:

答案 0 :(得分:0)

没有范围的小型可能解决方案(细胞的坐标可以根据您的需要进行更改):

Option Explicit
Sub check()
    Dim i As Integer, j As Integer
    Dim found As Boolean

    i = 1
    While Workbooks("A.xls").Sheets(1).Cells(i, 1).Value <> ""
        j = 1
        found = False
        While Workbooks("B.xls").Sheets(2).Cells(j, 13).Value <> ""

            If Workbooks("A.xls").Sheets(1).Cells(i, 1).Value = Workbooks("B.xls").Sheets(2).Cells(j, 13).Value Then found = True

            j = j + 1
        Wend

        If found = False Then
            Workbooks("A.xls").Sheets(1).Cells(i, 1).Interior.ColorIndex = 3
        End If
        i = i + 1
    Wend
End Sub