在两张纸上查找匹配值

时间:2018-08-02 09:23:57

标签: excel vba excel-vba loops

嗨,我正在尝试编写一个代码,其中检查column B on Sheet1中的每个值并在column A on Sheet 2中找到完全匹配的值,如果找到匹配项,则从{{1}复制整个行},并在Sheet 2上具有匹配值的行旁边。

我有以下代码(基于我在SO上找到的答案,但是当我尝试运行它时,即使有Sheet 1也会启动循环,但它仍会产生"Next without For"错误。

"For x"

3 个答案:

答案 0 :(得分:2)

这可能更接近您的目标。

Public Sub test()
    Dim x As Long
    Dim aNumber As Variant, rowNum As Variant, xfer As Variant
    Dim rng As Range, pwr As Worksheet

    Set pwr = Worksheets("PWRESET")
    Set rng = pwr.Columns(1)

    With Worksheets("REPORT")

        For x = 2 To .Cells(Rows.Count, "B").End(xlUp).row

            aNumber = .Cells(x, "B").Value
            rowNum = Application.Match(aNumber, rng, 0)
            If Not IsError(rowNum) Then
                With pwr
                    xfer = .Range(.Cells(rowNum, "A"), .Cells(rowNum, .Columns.Count).End(xlToLeft)).Value
                End With
                .Cells(x, "C").Resize(UBound(xfer, 1), UBound(xfer, 2)) = xfer
            End If

        Next x

    End With

End Sub

答案 1 :(得分:1)

删除其他项

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long
    Dim rep As Worksheet
    Dim pwr As Worksheet

    Set rep = Sheets("REPORT")
    Set pwr = Sheets("PWRESET")

    Application.ScreenUpdating = False

    lastrow = rep.Cells(Rows.Count, "B").End(xlUp).Row
    For x = 2 To lastrow    
        aNumber = rep.Range("B" & x).Value       
        Set rng = pwr.Range("A1:A2000")

        If Not IsError(Application.Match(aNumber, rng, 0)) Then
            rowNum = Application.Match(aNumber, rng, 0)
        End If
    'If your condition is not matched, your code will move on either way... you almost had it ;)         
    Next x

    Application.ScreenUpdating = True
End Sub

答案 2 :(得分:0)

您在其他位置之后使用了Next。...因此您出错了

Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
Dim rep As Worksheet
Dim pwr As Worksheet

    Set rep = Sheets("REPORT")
    Set pwr = Sheets("PWRESET")

        Application.ScreenUpdating = False

            lastrow = rep.Cells(Rows.Count, "B").End(xlUp).Row
            For x = 2 To lastrow

                aNumber = rep.Range("B" & x).Value

                Set rng = pwr.Range("A1:A2000")

                    If Not IsError(Application.Match(aNumber, rng, 0)) Then
                        rowNum = Application.Match(aNumber, rng, 0)
                    Else
                        Goto NextIteration
                    End If
                NextIteration:
            Next x

    Application.ScreenUpdating = True

End Sub

但是,您最好放弃其他所有内容(如已经在评论中所述)

相关问题