【问题标题】:VBA copy rows that meet criteria to another sheetVBA将符合条件的行复制到另一个工作表
【发布时间】:2014-01-31 05:31:05
【问题描述】:

我是 VBA 新手...如果该行中的第一个单元格显示 X,我想将一行从 Sheet2 复制到 Sheet1,然后对所有符合此条件的行执行此操作。我在 If 条件中有一个错误...我不知道如何解决它。

Sub LastRowInOneColumn()
'Find the last used row in a Column: column A in this example
    Worksheets("Sheet2").Activate
    Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
    MsgBox (LastRow)
    For i = 1 To LastRow
    If Worksheet.Cells(i, 1).Value = "X" Then
    ActiveSheet.Row.Value.Copy _
    Destination:=Hoja1
    End If
    Next i
 End Sub

【问题讨论】:

  • 试试AUTOFILTER
  • 如果我知道编程我会...我已经学习 VBA ...两天了 :) 这是一种我可以理解代码的方式...

标签: excel copy-paste vba


【解决方案1】:

您需要指定工作集。换行

If Worksheet.Cells(i, 1).Value = "X" Then

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

尝试使用以下代码(但这不是最好的方法。正如@SiddharthRout 建议的那样,考虑使用Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

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

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

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

【讨论】:

  • + 1 因为它回答了问题:) 但是绝对不是复制行的最佳方法,因为它在循环中这样做。正如我在上面的评论中提到的那样,Autofilter 是最好的选择。
  • 谢谢,但现在我有一个新的错误: ActiveSheet.Row.Value.Copy _ Destination:=Sheet1 .... 它说对象不承认这种礼仪或方法。 .
  • @SiddharthRout,我完全同意你的看法!在这种情况下,自动过滤器将是最好的。
  • @user3187303:你还需要把ActiveSheet.Row.Value.Copy改成Worksheets("Sheet2").Rows(i).Copy
  • @user3187303,Hoja1 是什么?
【解决方案2】:

在将之前的答案格式化为我自己的代码后,如果您尝试将通过AutoFilter 返回的值粘贴到单独的工作表中,我找到了一种复制所有必要数据的有效方法。

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

在此块中,AutoFilter 查找包含 strSearch 值的所有行并过滤掉所有其他值。然后它复制单元格(如果有标题,则使用偏移量),打开目标工作表并将值粘贴到目标工作表上的指定范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2016-11-19
    相关资源
    最近更新 更多