To combine data from multiple sheets into one sheet using a VBA macro

Step 1: Open the VBA Editor

  1. Open your Excel workbook.
  2. Go to the Developer tab and click on Visual Basic (or press Alt + F11).

Step 2: Insert a New Module

  1. In the VBA editor, click Insert in the top menu.
  2. Select Module to create a new module.

Step 3: Write the VBA Code to Combine Sheets

Here’s a simple VBA code that combines all sheets in your workbook into one:

Sub CombineSheetsWithDifferentColumns()
Dim ws As Worksheet
Dim masterSheet As Worksheet
Dim lastRowMaster As Long
Dim lastRowSource As Long
Dim lastColSource As Long
Dim pasteRow As Long

' Create or Clear a MasterSheet for combined data
On Error Resume Next
Set masterSheet = Sheets("MasterSheet")
On Error GoTo 0

If masterSheet Is Nothing Then
Set masterSheet = Worksheets.Add
masterSheet.Name = "MasterSheet"
Else
masterSheet.Cells.Clear
End If

pasteRow = 1 ' Row to start pasting in the MasterSheet

' Loop through each worksheet in the workbook
For Each ws In ThisWorkbook.Worksheets
' Skip the MasterSheet itself
If ws.Name <> "MasterSheet" Then
' Find the last row and column with data in the source sheet
lastRowSource = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
lastColSource = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

' If there is data, copy it
If lastRowSource > 1 Then
' Copy data from the current sheet to the MasterSheet
ws.Range(ws.Cells(1, 1), ws.Cells(lastRowSource, lastColSource)).Copy
masterSheet.Cells(pasteRow, 1).PasteSpecial xlPasteAll

' Move to the next row in MasterSheet
pasteRow = masterSheet.Cells(masterSheet.Rows.Count, 1).End(xlUp).Row + 1
End If
End If
Next ws

' Optional: Autofit columns to adjust widths
masterSheet.Columns.AutoFit

MsgBox "All sheets have been combined into 'MasterSheet'."
End Sub

Step 4: Run the Macro

  1. Close the VBA editor and return to Excel.
  2. Press Alt + F8 to open the Macro dialog box.
  3. Select CombineSheets and click Run.

Step 5: Review the Combined Data

  • The macro will create a new sheet named “MasterSheet” where all the data from the other sheets is combined.
  • If the “MasterSheet” already exists, it will be cleared and refilled with the new data.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *