Pages

Saturday, May 19, 2012

Merge Series ----- Merge data from all sheets from multiple workbooks and paste them in single worksheet

If you want to copy data from all sheets from multiple workbooks and paste them in single worksheet.

For example I have multiple workbooks stored in a folder. Like
a.xlsx
b.xlsx
c.xlsx
d.xlsx

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 copy data from all worksheets from multiple workbooks and paste to “data” sheet.


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 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

' SHOW FOLDER DAILOG BOX
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Choose the folder"
'.InitialFileName = "c:\"
.Show
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
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 Each wks In WKB.Sheets
w = wks.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
wks.Range(stcol & "2:" & lastcol & w).Copy _
Destination:=ThisWorkbook.Sheets(1).Range("a65356").End(xlUp).Offset(1, 0)
End If
Next
WKB.Close
End If
Next
MsgBox "Done"
Application.StatusBar = False
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub




Download Macro
Source Files

No comments:

Post a Comment