Consolidate Data Using VBA

How to consolidate data automatically using VBA. We have used the DSUM worksheet function and an array to automate the process of consolidation of data from multiple worksheets. The array of employee names is used in the criteria range of the Dsum function which helps in the automation of consolidating the salaries and the perks of the employees. First we get the data from multiple sheets into a new worksheet. In the new worksheet we can easily and quickly sum the relevant data for each employee. Watch the video below:

Watch this video on YouTube.

Here’s the complete VBA to consolidate data from multiple worksheets:

Sub consolidateDataUsingArray()
Dim empNames As Variant
Dim lastrow As Long
lastrow = Sheets(“Sheet2”).Range(“A” & Rows.Count).End(xlUp).Row

Dim rng As Range
Set rng = Sheets(“sheet5”).Range(“A2:A” & lastrow)
empNames = rng

For i = LBound(empNames) To UBound(empNames)
Range(“G2”) = empNames(i, 1)
Range(“L1”) = “employee Name”
Range(“M1”) = “Total Salary Paid”
Range(“N1”) = “Total Perks Paid”
j = i + 1
Cells(j, 12) = empNames(i, 1)
Cells(j, 13) = Application.WorksheetFunction.DSum(Range(“A1:C37”), 2, Range(“G1:I2”))
Cells(j, 14) = Application.WorksheetFunction.DSum(Range(“A1:C37”), 3, Range(“G1:I2”))

Next i

Columns(“A:I”).EntireColumn.Hidden = True

End Sub

Sub mergeData()
Dim j As Integer

On Error Resume Next
Worksheets.Add ‘ add a sheet
Sheets(1).Name = “MergedData”

‘ copy headers
Selection.Copy Destination:=Sheets(1).Range(“A1”)

‘ loop through sheets
For j = 2 To Sheets.Count

‘ header cells are not selected
Selection.Offset(1, 0).Resize(Selection.Rows.Count – 1).Select

‘ copy cells selected in the new sheet on the next blank row
Selection.Copy Destination:=Sheets(1).Range(“A65536”).End(xlUp)(2)


End Sub

Sub unhidecolumns()
Columns(“A:I”).EntireColumn.Hidden = False
End Sub

Sample file for download and practice: