Using VBA to merge multiple Excel files into one workbook saves hours of manual copy-paste work, especially when dealing with dozens of files with the same structure. This method consolidates data from separate workbooks into a single master sheet, preserving headers and formatting. You need Microsoft Excel with VBA enabled (Excel 2010 or later on Windows) and the files you want to merge must be in the same folder. All source files must have consistent column layouts for accurate merging.

What You'll Need

  • Microsoft Excel 2010 or later (Windows only; VBA is not supported in Excel for Mac in the same way)
  • Multiple Excel files (.xlsx or .xls) stored in a single folder
  • Each file must have identical column headers in the same order (e.g., Name, Date, Amount)
  • One blank Excel workbook to serve as the destination for merged data
  • Enable macros: Go to File > Options > Trust Center > Trust Center Settings > Macro Settings and select 'Enable all macros' temporarily during setup (revert after)

Step-by-Step

  1. Open a new, blank Excel workbook. This will be your master file where all data is merged.
  2. Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
  3. In the VBA editor, go to Insert > Module to create a new blank module.
  4. Copy and paste the following VBA code exactly as shown:
Sub MergeExcelFiles()
    Dim FolderPath As String
    Dim FileName As String
    Dim WS As Worksheet
    Dim MasterWS As Worksheet
    Dim LastRow As Long
    Dim NextRow As Long
    Dim wb As Workbook
    
    ' Set the folder path containing your Excel files
    FolderPath = "C:\YourFolderHere\" ' CHANGE THIS PATH
    
    ' Set the master worksheet - create one if needed
    On Error Resume Next
    Set MasterWS = ThisWorkbook.Worksheets("Master")
    If MasterWS Is Nothing Then
        Set MasterWS = ThisWorkbook.Worksheets.Add
        MasterWS.Name = "Master"
    End If
    On Error GoTo 0
    
    ' Clear existing data in Master sheet
    MasterWS.Cells.Clear
    
    ' Set first row as headers
    NextRow = 1
    
    ' Loop through all files in the folder
    FileName = Dir(FolderPath & "*.xlsx")
    Do While FileName <> ""
        Set wb = Workbooks.Open(FolderPath & FileName)
        
        For Each WS In wb.Worksheets
            ' Skip if sheet is empty
            If Application.WorksheetFunction.CountA(WS.Cells) > 0 Then
                ' Copy headers from first file only
                If NextRow = 1 Then
                    WS.Rows(1).Copy Destination:=MasterWS.Rows(NextRow)
                    NextRow = NextRow + 1
                End If
                
                ' Find last row in source sheet
                LastRow = WS.Cells(WS.Rows.Count, "A").End(xlUp).Row
                
                ' Copy data from row 2 to last row
                WS.Range("A2:" & WS.Cells(LastRow, WS.Columns.Count).Address).Copy Destination:=MasterWS.Cells(NextRow, 1)
                
                ' Update next row for next file
                NextRow = MasterWS.Cells(MasterWS.Rows.Count, "A").End(xlUp).Row + 1
            End If
        Next WS
        
        wb.Close SaveChanges:=False
        FileName = Dir
    Loop
    
    MsgBox "Merge complete! " & NextRow - 1 & " rows imported.", vbInformation
End Sub
  1. Replace C:\YourFolderHere\ with the full path to your folder containing Excel files (e.g., C:\Users\YourName\Documents\MergeFiles\). Use double backslashes (\) as separators.
  2. Save the master workbook as a macro-enabled file: File > Save As > Choose "Excel Macro-Enabled Workbook (*.xlsm)".
  3. Close the VBA editor and return to Excel.
  4. Press Alt + F8 to open the Macro dialog box.
  5. Select MergeExcelFiles and click Run.
  6. Wait for the process to complete. A message box will appear showing how many rows were imported.

Common Mistakes

  • Using single backslashes in the folder path (e.g., C:\Folder\) — use double backslashes (C:\\Folder\\) in VBA.
  • Forgetting to save the master workbook as .xlsm, which disables macros on next open.
  • Source files have mismatched column counts or headers in different positions — VBA assumes identical structure.
  • Running the macro on a folder containing non-Excel files — it will skip them, but may cause delays.
  • Leaving the "Master" sheet in the destination workbook already populated — the code clears it first, so backup if needed.
  • Opening the files in Excel while running the macro — this can cause file locks and errors.

Tips

  • Test first with 2–3 small files to confirm the output format before processing dozens.
  • Use a dedicated folder for merging — avoid mixing in files you don’t want to include.
  • Format your data in source files as tables (Ctrl + T) to help VBA detect ranges more reliably.
  • Remove any blank rows or merged cells in source sheets — they break row counting.
  • For large datasets (>10,000 rows), disable screen updating by adding Application.ScreenUpdating = False at the top and Application.ScreenUpdating = True at the bottom of the code.
  • Add Application.Calculation = xlCalculationManual at the start and Application.Calculation = xlCalculationAutomatic at the end to speed up processing if formulas exist.

Troubleshooting

  • Error: "Run-time error '1004': Unable to get the Match property of the WorksheetFunction class" — This means the folder path is invalid. Double-check the path format and that the folder exists.
  • Macro won't run: "Macro disabled" message — Re-enable macros: File > Options > Trust Center > Trust Center Settings > Macro Settings > Enable all macros. Save as .xlsm and reopen.
  • Only headers copied, no data — Verify your source files have data starting in row 2. If headers are in row 1 and data starts in row 3, change "A2" to "A3" in the code.
  • File not found error — Ensure all source files end in .xlsx or .xls. If using .xlsb, change "*.xlsx" to "*.*" and add an IF statement to skip non-Excel files.
  • Slow performance — Turn off screen updating and manual calculation as per the Tips section above.
  • Empty Master sheet after running — Check if the folder path is correct and files are in that exact folder. Also ensure files aren’t open in another Excel window.

Frequently Asked Questions

Can I merge Excel files from different folders?

No, this code only scans one folder. To merge from multiple folders, you’d need to modify the code to loop through folder paths or use a file dialog picker — which requires more advanced VBA.

Does this work with .csv files?

No, this code is designed for .xlsx and .xls files. To merge CSV files, you’d need to modify the file extension filter and use Workbooks.OpenText instead of Workbooks.Open.

What if my files have different column orders?

The code assumes identical column order. If column order differs, you must standardize the layout beforehand or rewrite the code to map columns by header name, which is significantly more complex.

Can I merge files with multiple sheets?

Yes — the code loops through every worksheet in each source file and merges them all into one "Master" sheet. Each sheet's data is appended in sequence.

Will formatting (colors, fonts) be preserved?

No, only values and formulas are copied. Formatting is not preserved. To retain formatting, you’d need to add additional .Copy and .PasteSpecial lines for formats, which increases complexity.

Is this compatible with Excel on Mac?

No, VBA support on Excel for Mac is limited and often incompatible with Windows VBA code. Use Windows Excel or alternative tools like Power Query for Mac users.