Monday 13 September 2021

Macro to consolidate data from multiple worksheets

When data are spread across multiple worksheets and one wanna put together everything in a  single sheet of the workbook, the following macro works.


Sub combinedata()
Dim var As Integer
Dim sh As Worksheet
var = 0
For Each sh In Worksheets
 If sh.Name = "Consolidated Data" Then
 var = 1
 Exit For
 End If
Next sh
If var = 0 Then Sheets.Add(Before:=Sheets(1)).Name = "Consolidated Data" Else
Sheets("Consolidated Data").Move Before:=Sheets(1)
Sheets(2).Activate
Sheets(2).Range(Range("a1"), Range("A1").End(xlToRight)).Copy
Sheets(1).Activate
Sheets("Consolidated Data").Paste Destination:=Range("a1")
For Each sh In Worksheets
 If sh.Name <> ActiveSheet.Name Then
 With sh
 .Range("A2:N" & .Range("A" & Rows.Count).End(xlUp).Row).Copy _
 Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1)
 End With
 End If
Next sh
ActiveWindow.DisplayGridlines = False
Range("A1").CurrentRegion.Select
Selection.Columns.AutoFit
End Sub


No comments:

Post a Comment