Search code examples
excelvbaloopsreferencecopy

How can I reference the active cell within a loop through different sheets?


I am stuck where it is properly reading that I have two rows that fulfill the "If" condition, but it is copying row 1 both times on separate sheets, rather than row 8 and 10. Is there a way to have it recognize one cell at a time and copy it if it fills the conditions.

I have tried the following code

Sub RunReport()
    Dim srcSheet As Worksheet
    Dim rptSheet As Worksheet
    Dim i As Range
    Dim srcSheets As Variant
    
        Set rptSheet = ThisWorkbook.Sheets("Report")
        Set srcSheets = Worksheets(Array("SheetA", "SheetB", "SheetC", "SheetD"))
        
        For Each srcSheet In srcSheets
            For Each i In srcSheet.Range("A5:W358")
                If srcSheet.Range(i, "B").Value <> "" And srcSheet.Range(i, "O").Value = "" Then
                    srcSheet.Cells(i).EntireRow.Copy Destination = rptSheet.Cells(rptSheet.Rows.Count, "A").End(xlUp).Offset(1, 0)
                End If
            Next i
        Next srcSheet
        
End Sub

Solution

  • Copy Matching Rows (2 Criteria)

    A Quick Fix

    Sub RunReport()
         
        Dim wb As Workbook: Set wb = ThisWorkbook
        
        Dim srcSheets As Sheets: Set srcSheets = wb.Sheets(Array( _
            "SheetA", "SheetB", "SheetC", "SheetD"))
        
        Dim rptSheet As Worksheet: Set rptSheet = wb.Sheets("Report")
        Dim rptCell As Range: Set rptCell = rptSheet _
            .Cells(rptSheet.Rows.Count, "A").End(xlUp).Offset(1)
        
        Dim srcSheet As Object, srcRange As Range, srcRow As Range
            
        For Each srcSheet In srcSheets
            If TypeOf srcSheet Is Worksheet Then
                Set srcRange = srcSheet.Range("A5:W358")
                For Each srcRow In srcRange.Rows
                    If Len(CStr(srcRow.Columns("B").Value)) > 0 _
                            And Len(CStr(srcRow.Columns("O").Value)) = 0 Then
                        srcRow.Copy Destination:=rptCell
                        Set rptCell = rptCell.Offset(1)
                    End If
                Next srcRow
            End If
        Next srcSheet
            
    End Sub