excelvbaloops

Creating loops to pull data from different worksheets using VBA?


I'm new to VBA code. I'm trying to create a loop where I copy cells E8:E16 from 6 different worksheets and past them into a "master" work sheet. This range does not change at all. I'm having trouble when it comes to pasting the values into the "master" worksheet. I would like the pasted values to start and end at C4:C12, then D4:D12, etc. Can anyone help? Here is the code I currently have:

Sub WeekpayLoop()

Dim ws As Worksheet

    For Each ws In Worksheets
        If ws.Name <> "Praticeruns" Then
            ws.Range("E8:E16").Copy
            ActiveSheet.Paste Range("C4:C12")
        End If
    Next ws

End Sub

The only success I've gotten so far was using this code: Old VBA Code

However, when I run this code the formatting is off as all copied values are listed in column A.


Solution

  • If you just need to move the paste destination over to the right for each sheet:

    Sub WeekpayLoop()
    
        Dim wb As Workbook, ws As Worksheet, rngPaste As Range
    
        Set wb = ThisWorkbook  'or ActiveWorkbook, etc
        
        'start pasting here...
        Set rngPaste = wb.Worksheets("Praticeruns").Range("C4")
        
        Debug.Print "Checking workbook: " & wb.Name
        For Each ws In wb.Worksheets
            If ws.Name <> rngPaste.Parent.Name Then
                Debug.Print ,"Worksheet: " & ws.Name
                ws.Range("E8:E16").Copy rngPaste
                Set rngPaste = rngPaste.Offset(0, 1) 'next column to the right
            End If
        Next ws
    
    End Sub