【问题标题】:VBA copy mutlipe rows that meet criteria to another sheetVBA将满足条件的多行复制到另一个工作表
【发布时间】:2019-07-03 22:53:59
【问题描述】:

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

我有一个分配到特定航班 (LEGID) 的人员列表,我想将这些人员 (工作表 pax) 复制到另一个工作表中的特定单元格 (temp - 单元格 b15),但它不起作用。

此数据表是来自 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

【问题讨论】:

  • 您是否收到错误或没有复制任何内容?
  • 如果数据存储在表中,我认为您将希望使用ListObject 而不是循环遍历一个范围。
  • 没有错误。只是不要做任何事情。 - @Warcupine
  • 我该怎么做? @ZackE
  • 看第二个答案Here

标签: excel vba


【解决方案1】:

如果您只想复制名称。你可以用这个;但是,如果它们是命名范围,您将需要更新工作表名称和范围。此代码在 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

【讨论】:

  • 谢谢@zack e。您的代码不适用于我的 Excel。所以我尝试将部分表格复制到一个新的 excel 中,我的代码和你的代码正在运行。所以我的问题是。该代码不适用于查询表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-31
  • 2021-04-10
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
相关资源
最近更新 更多