Excel VBA looping through multiple worksheets

You should be declaring rng for each ws inside the loop, like:

Sub exercise()
    Dim ws As Worksheet
    Dim rng As Range

    For Each ws In ActiveWorkbook.Worksheets
        'Finding last row in column B
        Set rng = ws.Range("B" & ws.Rows.Count).End(xlUp) '<~~ Moved inside the loop
        'Don't copy data from xws worksheet
        If ws.Name <> "xws" Then
            'Storing first copied data in A1
            If IsEmpty(Sheets("xws").[A1]) Then
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp)
            'Storing next copied data below previously filled cell
            Else
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            End If
        End If
    Next ws
End Sub

As your code is now, rng will be pointing to the ActiveSheet at the time you run the macro, and your code will then copy the same cell on each iteration of the code.

Leave a Comment