VBA在几个不同的工作表中搜索和匹配值

时间:2017-12-03 21:28:29

标签: excel-vba search match vba excel

我设法编写代码来搜索,匹配和导入工作表(“检查数据库”)和工作表(“Civil DB”)之间的某些值。

For rw = 2 To .Cells(.Rows.Count, "C").End(xlUp).row
        mtch = Application.Match(.Cells(rw, "C").Value, wsc.Columns("A"), 0)

未找到的值将转到工作表(“搜索”)

   If IsError(mtch) Then
            .Cells(rw, "E") = .Cells(rw, "B").Value & " " & .Cells(rw, 
   "C").Value
             wser.Cells(rw, "N") = .Cells(rw, "B").Value
             wser.Cells(rw, "O") = .Cells(rw, "C").Value

如何添加代码 将搜索工作表中的列(“搜索”)以及第二个工作表中的列(工作表(“Airliners”)

    Dim rw As Long, mtch As Variant, wsc As Worksheet

    Set wsc = Worksheets("Civil DB")
    Set wser = Worksheets("Search")
    Set wsa = Worksheets("Airliners")

    With Worksheets("Check Database")
        For rw = 2 To .Cells(.Rows.Count, "C").End(xlUp).row
            mtch = Application.Match(.Cells(rw, "C").Value, wsc.Columns("A"), 0)


          ????????????


            If IsError(mtch) Then
                .Cells(rw, "E") = .Cells(rw, "B").Value & " " & .Cells(rw, "C").Value
                 wser.Cells(rw, "N") = .Cells(rw, "B").Value
                 wser.Cells(rw, "O") = .Cells(rw, "C").Value

            Else
                .Cells(rw, "D") = wsc.Cells(mtch, "B").Value


            End If
        Next rw

1 个答案:

答案 0 :(得分:1)

假设您只想检查(并使用)“Airliners”表格,如果“Civil DB”表格中没有匹配项,我认为您是在追求:

'...
For rw = 2 To .Cells(.Rows.Count, "C").End(xlUp).row
    mtch = Application.Match(.Cells(rw, "C").Value, wsc.Columns("A"), 0)
    If IsError(mtch) Then
        'No match found in Civil DB, try in Airliners
        mtch = Application.Match(.Cells(rw, "C").Value, wsa.Columns("A"), 0)
        If IsError(mtch) Then
            'No match in Airliners either, so treat as error
            .Cells(rw, "E") = .Cells(rw, "B").Value & " " & .Cells(rw, "C").Value
             wser.Cells(rw, "N") = .Cells(rw, "B").Value
             wser.Cells(rw, "O") = .Cells(rw, "C").Value

        Else
            'Match in Airliners, so store value
            .Cells(rw, "D") = wsa.Cells(mtch, "B").Value
        End If
    Else
        'Match in Civil DB, so store value
        .Cells(rw, "D") = wsc.Cells(mtch, "B").Value
    End If
Next rw