VBA将符合条件的多行复制到另一张工作表

时间:2019-07-03 12:53:33

标签: excel vba

我真的不太了解VBA,所以请耐心等待。

我有一个分配给特定航班(LEGID)的人员列表,我想将这些人员(Worksheet pax)复制到另一个工作表中的特定单元格(temp-单元格b15),但这是行不通的。 / p>

此数据表是来自salesforce的查询报告。

Sub pax()

   Dim LastRow As Long
   Dim i As Long, j As Long
   Dim legid As String

Application.ScreenUpdating = False

legid = ThisWorkbook.Worksheets("setup").Range("SelReq").Value

Debug.Print legid


   'Find the last used row in a Column: column A in this example
   With Worksheets("pax")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

'   MsgBox (LastRow)
   'first row number where you need to paste values in temp'
   With Worksheets("temp")
      j = .Cells(.Rows.Count, "a").End(xlUp).Row + 1
   End With

   For i = 1 To LastRow
       With Worksheets("pax")
           If .Cells(i, 1).Value = legid Then
               .Rows(i).Copy Destination:=Worksheets("temp").Range("a" & j)
               j = j + 1
           End If
       End With
   Next i

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

如果您只想复制名称。您可以使用它;但是,如果您将图纸名称和范围命名为range,则需要更新它们。此代码在Sheet3上的某个特定单元格中查找值,然后,如果该值与Sheet1上某个范围内的值匹配,它将把Sheet1上B列的值放入Sheet2

Sub Test()
    Dim cell As Range
    Dim LastRow As Long, i As Long, j As Long
    Dim legid As String


    With Sheet1
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    With Sheet2
        j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    legid = Sheet3.Range("A1")

    For i = 2 To LastRow
        For Each cell In Sheet1.Range("A" & i)
            If cell.Value = legid Then
                Sheet2.Range("A" & j) = cell.Offset(0, 1).Value
                j = j + 1
            End If
        Next cell
    Next i

End Sub