VBA macros · Workbooks and files
VBA macro to merge all workbooks in a folder into one sheet
Combine the first sheet of every Excel file in a folder into one sheet, stacked below each other with a column showing which file each row came from.
Every month the branches send in a file with the same columns, and someone has to paste them all into one list. This macro asks for the folder, opens every Excel file in it read-only, copies the data rows of the first sheet into one new workbook, and adds a column with the source file name, so you can always trace a row back.
Option Explicit
Sub MergeWorkbooksInFolder()
Dim folder As String, f As String
Dim target As Worksheet
Dim wb As Workbook
Dim src As Worksheet
Dim lastRow As Long, lastCol As Long, nextRow As Long
Dim files As Long
Dim headerDone As Boolean
folder = PickFolder()
If Len(folder) = 0 Then Exit Sub
If Right$(folder, 1) <> Application.PathSeparator Then folder = folder & Application.PathSeparator
Set target = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
target.Name = "Merged"
nextRow = 2
On Error GoTo Fail
Application.ScreenUpdating = False
Application.EnableEvents = False ' no Workbook_Open macros in the sources
Application.DisplayAlerts = False
f = Dir(folder) ' every file; filtered below
Do While Len(f) > 0
If LCase$(f) Like "*.xls*" And Left$(f, 2) <> "~$" And f <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(folder & f, UpdateLinks:=0, ReadOnly:=True)
Set src = wb.Worksheets(1)
lastRow = LastUsedRow(src)
lastCol = src.Cells(1, src.Columns.Count).End(xlToLeft).Column
If Not headerDone Then ' headings from the first file
target.Cells(1, 1).Value = "Source file"
target.Cells(1, 2).Resize(1, lastCol).Value = src.Cells(1, 1).Resize(1, lastCol).Value
headerDone = True
End If
If lastRow >= 2 Then ' values only, rows 2..lastRow
target.Cells(nextRow, 2).Resize(lastRow - 1, lastCol).Value = _
src.Range(src.Cells(2, 1), src.Cells(lastRow, lastCol)).Value
target.Cells(nextRow, 1).Resize(lastRow - 1, 1).Value = f
nextRow = nextRow + lastRow - 1
End If
wb.Close SaveChanges:=False
Set wb = Nothing
files = files + 1
End If
f = Dir()
Loop
target.Columns.AutoFit
Done:
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox files & " file(s) merged, " & nextRow - 2 & " row(s).", vbInformation
Exit Sub
Fail:
If Not wb Is Nothing Then wb.Close SaveChanges:=False
MsgBox "Problem with '" & f & "': " & Err.Description, vbExclamation
Resume Done
End Sub
Private Function LastUsedRow(ws As Worksheet) As Long
Dim c As Range
Set c = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not c Is Nothing Then LastUsedRow = c.Row
End Function
Private Function PickFolder() As String
' Windows: folder dialog. Mac: type or paste the path.
#If Mac Then
PickFolder = InputBox("Full path of the folder:", "Pick a folder", ThisWorkbook.Path)
#Else
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Pick a folder"
If .Show = -1 Then PickFolder = .SelectedItems(1)
End With
#End If
End FunctionHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickMergeWorkbooksInFolderand click Run. - Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.
How it works
PickFolder shows Excel's folder dialog on Windows. Dir(folder) returns the first file name in that folder and every later call of Dir() without arguments returns the next one, until it returns an empty string. The macro lists all files and checks the extension itself with Like "*.xls*", which catches .xls, .xlsx, .xlsm and .xlsb files. Temporary lock files that start with ~$ and the macro's own workbook are skipped.
Each file is opened with ReadOnly:=True and UpdateLinks:=0, so the sources are never changed and no link questions appear. EnableEvents = False stops any Workbook_Open code inside them from running.
The last row is found with Find("*", SearchDirection:=xlPrevious), which looks backwards from A1 and therefore lands on the last row that contains anything, even when column A has gaps. The data rows are copied as values with a direct Value = Value assignment between two ranges of the same size, which is faster than copy and paste and leaves the clipboard alone. Column A of the result gets the file name for every copied row.
The Fail handler closes a file that could not be read, reports it and then continues at Done so Excel's settings are always restored. Folder loops are explained in Files and folders: open, save, loop through files and write text files.
Change it
Common changes:
- Use a sheet by name instead of the first sheet:
Set src = wb.Worksheets("Data"). - Only CSV files: change the test to
LCase$(f) Like "*.csv". A CSV opens as a workbook with one sheet, so the rest works unchanged. - Keep formats too: replace the value assignment with
src.Range(...).Copy target.Cells(nextRow, 2). This is slower and the formats of the first file win. - Data starting lower down, for example headings in row 4: replace the 1s and 2s that refer to rows with 4 and 5.
If the files are spread across several sheets each, combine them inside each file first with VBA macro to combine all sheets into one sheet in Excel, or loop over wb.Worksheets inside the file loop.
What can go wrong
src.Cells(1, 1).Resize(1, lastCol) with the first file's headings before copying.A very large folder can hit Excel's row limit of 1,048,576. Files protected with a password stop at the open step and are reported. On a Mac, FileDialog does not exist, so the #If Mac Then branch asks for the folder path in an input box instead (for example /Users/anna/Documents/Reports). Excel for Mac is sandboxed: the first time a macro opens files in a folder, macOS may ask you to grant access to it. Click Grant Access.
Related: VBA macro to combine all sheets into one sheet in Excel, VBA macro to list all files in a folder in Excel, Files and folders: open, save, loop through files and write text files.