Saturday, May 19, 2012

Merge Series ----- Merge data from multiple workbooks for specific sheets only and paste them in one sheet of new workbook

If you want to merge data from multiple workbooks for specific sheets only and paste them in single worksheet.

For example I have multiple workbooks stored in a folder. Like

And each workbook is having multiple worksheets Jan, Feb, Mar etc., and you have created a new workbook with sheet "Data". Now you want to consolidate all data from Feb. and mar worksheets from multiple workbooks to "data" tab of new workbook.

Here is the code-

Option Explicit
Option Explicit
Sub merge_multiple_workbooks()
Dim fldpath
Dim fld, fil, FSO As Object
Dim WKB As Workbook
Dim wks As Worksheet
Dim shtnames()
Dim Paste
Dim j As Long, w As Long
Dim stcol As String, lastcol As String

stcol = "A" ' Change the starting column of ur data
lastcol = "C" ' Change the ending column of ur data

With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Choose the folder"
'.InitialFileName = "c:\"
End With
On Error Resume Next
fldpath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
If fldpath = False Then
MsgBox "Folder Not Selected"
Exit Sub
End If
' change sheet names here
shtnames = Array("Feb", "Mar") '\ add or remove sheets
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.StatusBar = True
Application.StatusBar = "Please wait till Macro merge all the files"
Set FSO = CreateObject("scripting.filesystemobject")
Set fld = FSO.getfolder(fldpath)

' browse through all files in source folder
For Each fil In fld.Files
If UCase(Right(fil.Path, 5)) = UCase(".xlsx") And fil.Name <> ThisWorkbook.Name Then
Set WKB = Workbooks.Open(fil.Path)
For j = LBound(shtnames) To UBound(shtnames)
For Each wks In WKB.Sheets
If wks.Name = shtnames(j) Then
w = WKB.Sheets(shtnames(j)).Range("a65356").End(xlUp).Row
' stcol - starting column of my range eg - a
'2 - as my data will start from row 2 because i do not want to copy headers again and again
'lastcol - end column of range eg - c
' w - last filled row in sheet/ ending row of my data
If w >= 2 Then
WKB.Sheets(shtnames(j)).Range(stcol & "2:" & lastcol & w).Copy _
Destination:=ThisWorkbook.Sheets(1).Range("a65356").End(xlUp).Offset(1, 0)
End If
Exit For
End If
End If
MsgBox "Done"
Application.StatusBar = False
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Download Source Files

Download Macro

No comments:

Post a Comment

Import data from SQL

Macro to import data from SQL using ADO connection string: Sub Import_data_from_SQL() ' Tools -> References -> Microsoft Active...