Search code examples
excelvbaloopscopy-paste

Copy a range from sheet 1 and paste to next empty row on next sheets in loop


I'm trying to copy a range on a sheet called "template", go to the next sheet, find the next available row and paste the copied range. Then go up 7 rows, select 7 rows down to hide those rows so only the new 7 rows i've pasted are visible. But I need to exclude the sheet called "template" and one called "timecard" Thank you for your help. All parts work fine but it is not going to the next worksheet, it stays on "template" (sheet i'm copying range from). This is what i have so far:

Sub TimeCardReset()
Dim sh As Worksheet

Sheets("Template").Activate
Range("A3:G9").Select
Selection.Copy
            
For Each sh In ThisWorkbook.Worksheets
        If sh.Name = "TEMPLATE" Then
        ' do nothing
        ElseIf sh.Name = "TimeCard" Then
        ' do nothing
        Else
           Range("A" & Rows.Count).End(xlUp).Select
           ActiveCell.Offset(1, 0).Select
           ActiveSheet.Paste
           ActiveCell.Offset(-7, 0).Select
           '   Select current row through 6 rows and hide those rows
           ActiveCell.Resize(7, 1).EntireRow.Hidden = True
        End If
Next sh
Application.CutCopyMode = False
End Sub

Solution

  • To simplify your code; use the With Statement, to get rid of Select, Activate, and ActiveSheet. If you only want to copy the values to the other worksheet, you don't need to use an Array or excessive Variables to accomplish your task, you can just set the destination range equal to the source range, which is faster because it bypasses the clipboard entirely. The lRow variable is used as a reference point for both lines of code.

    Dim ws As Worksheet, lRow As Long
    
        For Each ws In ThisWorkbook.Sheets 'loop through all the worksheets
            If ws.Name <> "Template" And ws.Name <> "TimeCard" Then 'skip these worksheets
                
                With ws 'to avoid using Select, ActiveCell, and ActiveSheet
    
                    lRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Set the last row for the current ws
                  
                    'Added - This line will copy both formulas and values
                    ThisWorkbook.Sheets("Template").Range("A3:G9").Copy Destination:=.Cells(lRow, "A").Offset(1)
                    
                    'Deleted - use lRow, Offset, and Resize to set the range on destination sheet to match the range on the "Template" worksheet
                    'Deleted - .Cells(lRow, "A").Offset(1).Resize(7, 7).Value = ThisWorkbook.Sheets("Template").Range("A3:G9").Value
                    
                    'Use lRow, Offset and Resize to to select the rows you want to hide
                    .Cells(lRow, "A").Offset(-6).Resize(7).EntireRow.Hidden = True
                End With
            End If
        Next ws