Question

Looking to copy rows from all sheets apart from my active sheet that meet a certain criteria in column J using VBA.

Not experienced in writing code in VBA so I have tried to frankenstein together the necessary parts from looking through other questions and answers;

below is the code I have written so far;

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

Where Controlled is the sheet I want the data to appear in from the other sheets, and all other sheets are searched to see if their column J meets the criteria="Y"

I won't need to copy over formatting as all Sheets will have the formatting exactly the same and if possible I want the rows that are copied over to start at row 3

Was it helpful?

Solution

Try this:

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

I think this covers everything or most of your requirement.
Not tested though so I leave it to you.
If you come across with problems, let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top