Excel 函数。在循环中匹配

Excel 函数。在循环中匹配,excel,vba,loops,match,Excel,Vba,Loops,Match,我试图将单元格(grid_2.range“A1”)和grid_2.range(“B1”)中的值与名为grid_2(“Grid2”)的工作表上的列p进行匹配,以复制该值所在的所有行。因此,我需要检查我的数据,并将整行复制/粘贴到另一个工作表maned网格中。但由于某些原因,我的代码循环,但只找到匹配项并复制粘贴一次 Sub new_copyPaste() Dim targetSh As Worksheet Dim i As Variant Dim lastRow As L

我试图将单元格
(grid_2.range“A1”)
grid_2.range(“B1”)
中的值与名为grid_2(“Grid2”)的工作表上的列p进行匹配,以复制该值所在的所有行。因此,我需要检查我的数据,并将整行复制/粘贴到另一个工作表maned网格中。但由于某些原因,我的代码循环,但只找到匹配项并复制粘贴一次

Sub new_copyPaste()

    Dim targetSh As Worksheet
    Dim i As Variant
    Dim lastRow As Long
    
    
    lastRow = grid.Cells(Rows.Count, "C").End(xlUp).Row + 1
 
    
    For i = 3 To grid_2.Cells(Rows.Count, "P").End(xlUp).Row
        Position = WorksheetFunction.Match(grid_2.Range("A1"), Worksheets("Grid2").Columns(16), 0)
          If grid_2.Cells(i, 16).Value = grid_2.Range("A1") Then
           Worksheets("Grid2").Rows(Position).Copy
           grid.Range("A" & lastRow).PasteSpecial
        End If
    Next i
    
        
    For i = 3 To grid_2.Cells(Rows.Count, "P").End(xlUp).Row
    Position = WorksheetFunction.Match(grid_2.Range("B1"), Worksheets("Grid2").Columns(16), 0)
    
        If grid_2.Cells(i, 16).Value = grid_2.Range("B1") Then
           Worksheets("Grid2").Rows(Position).Copy
           grid.Range("A" & lastRow).PasteSpecial
        End If
    Next i
    
End Sub
也许你知道我做错了什么

我曾想过使用VLookup,但经过研究,似乎函数匹配更合适。
我愿意接受建议:)

Match只返回第一个匹配项,此处不需要:

Sub new_copyPaste()

    
    Dim lastRow As Long
    Dim i As Long
    For i = 3 To grid_2.Cells(Rows.Count, "P").End(xlUp).Row
          If grid_2.Cells(i, 16).Value = grid_2.Range("A1") Then
           Worksheets("Grid2").Rows(i).Copy
           lastRow = grid.Cells(Rows.Count, "C").End(xlUp).Row + 1
           grid.Range("A" & lastRow).PasteSpecial
        End If
    Next i
    
    For i = 3 To grid_2.Cells(Rows.Count, "P").End(xlUp).Row
        If grid_2.Cells(i, 16).Value = grid_2.Range("B1") Then
           Worksheets("Grid2").Rows(i).Copy
           lastRow = grid.Cells(Rows.Count, "C").End(xlUp).Row + 1
           grid.Range("A" & lastRow).PasteSpecial
        End If
    Next i
    
End Sub