Excel VBA使用自动筛选器复制行

时间:2014-02-27 02:36:46

标签: vba excel-vba autofilter excel

希望使用VBA复制除活动工作表之外的所有工作表中的行,这些工作表符合J列中的特定条件。

在VBA编写代码方面没有经验,所以我尝试将frankenstein与其他问题和答案一起讨论必要的部分;

下面是我到目前为止编写的代码;

Sub CommandButton1_Click()

  Dim lngLastRow As Long
  Dim ws As Worksheet
  Dim r As Long, c As Long
  Dim wsRow As Long

  Set Controlled = Sheets("Controlled") ' Set This to the Sheet name you want all Ok's     going to

  Worksheets("Controlled").Activate
  r = ActiveSheet.Cells(Rows.Count, 2).End(x1up).Row
  c = ActiveSheet.Cells(1, Columns.Count).End(x1ToLeft).Column
  Range("J").AutoFilter

  For Each ws In Worksheets
    If ws.Name <> "Controlled" Then
       ws.Activate
       wsRow = ActiveSheet.Cells(Rows.Count, 2).End(x1up).Row + 1
       Range("A" & r).AutoFilter Field:=10, Criteria1:="Y"
       .Copy Controlled.Range("A3" & wsRow)
    End If 
  Next ws
End If


Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub

在受控制的情况下,我希望数据从其他工作表中显示,并搜索所有其他工作表以查看其列J是否符合条件=“Y”

我不需要复制格式,因为所有表格格式都完全相同,如果可能,我希望复制的行从第3行开始

1 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit
Sub ConsolidateY()

Dim ws As Worksheet, wsCtrl As Worksheet
Dim lrow As Long, rng As Range

Set wsCtrl = Thisworkbook.Sheets("Controlled")

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

For Each ws In Thisworkbook.Worksheets
    If ws.Name = "Controlled" Then GoTo nextsheet
    With ws
        lrow = .Range("J" & .Rows.Count).End(xlUp).Row
        .AutoFilterMode = False
        Set rng = .Range("J1:J" & lrow).Find(what:="Y", after:=.Range("J" & lrow))
        If rng Is Nothing Then GoTo nextsheet
        .Range("J1:J" & lrow).AutoFilter Field:=1, Criteria1:="Y"
        .Range("J1:J" & lrow).Offset(1,0).SpecialCells(xlCellTypeVisible).EntireRow.Copy
        wsCtrl.Range("A" & wsCtrl.Rows.Count).End(xlUp).Offset(1,0).PasteSpecial xlPasteValues
        .AutoFilterMode = False
        Application.CutCopyMode = False
    End With
nextsheet:
Next

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub

我认为这涵盖了您的一切或大部分要求 虽然没有经过测试,但我还是留给你了 如果您遇到问题,请告诉我。