5 Ways to Merge Excel Files via CMD
If you frequently work with Microsoft Excel, you understand how time-consuming and manual the process of merging multiple Excel files can be. Whether you're compiling data from various sources or looking to streamline your reporting processes, automation is key. Fortunately, command-line tools provide an efficient way to automate Excel file merging, enhancing productivity significantly. Here are five comprehensive methods to merge Excel files via Command Prompt (CMD):
Method 1: Using Batch Script
A batch script allows you to automate tasks by running several commands in sequence. To merge Excel files:
- Open Notepad.
- Copy and paste the following script:
@echo off setlocal enabledelayedexpansion REM Define path to your Excel files set "path=C:\Excel Files\" REM Temporary file for merging set "tempFile=merged.xlsx" REM Get list of Excel files dir /b /s "%path%*.xlsx" > fileList.txt REM Merge files ( echo Package echo Part SourcePackage for /f "tokens=*" %%i in (fileList.txt) do echo ContentType Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for /f "tokens=*" %%i in (fileList.txt) do ( echo Copy Files\[%%i] for /r %%j in (%%i) do ( set "file=%%j" set "file=!file:%path%=!" echo Copy Files\!file! ) ) echo EndPackage ) > combine.txt REM Convert the text file into a valid Excel macro-enabled workbook copy /y %path%xl\workbook.xml combine.txt copy /y %path%combine.txt "%path%\!tempFile!" move /y %path%\!tempFile! "%path%merged.xlsm" echo "Merged Excel File created at %path%merged.xlsm" pause
When run, this batch file will merge all .xlsx files from the specified directory into a single Excel macro-enabled workbook named "merged.xlsm".
Method 2: Power Automate (Microsoft Flow)
Power Automate (formerly known as Microsoft Flow) is an online workflow service that can automate tasks in Excel Online:
- Create a new flow in Power Automate.
- Choose "Manually trigger a flow".
- Add an "OneDrive for Business" connector action named "List files in a folder" to find your Excel files.
- Add an "Excel Online (Business)" connector, choose "Merge workbooks" action.
- Configure the action to merge the files listed previously.
- Run the flow manually to merge the files.
Method 3: PowerShell Script
PowerShell offers robust scripting capabilities for Windows:
$files = Get-ChildItem -Path "C:\Excel Files\*.xlsx" $merged = "C:\Excel Files\merged.xlsx" Start-Process "powershell.exe" -ArgumentList "-NoProfile -Command Get-ExcelWorkbookData -WorkbookPath $($files[0].FullName) | Out-Excel -Path $merged -WhatIf -AutoSize" for ($i=1; $i -lt $files.Count; $i++) { Start-Process "powershell.exe" -ArgumentList "-NoProfile -Command Get-ExcelWorkbookData -WorkbookPath $($files[$i].FullName) | Out-Excel -Path $merged -Append -WhatIf -AutoSize" }
Save this script as a .ps1 file and run it in PowerShell to merge the files.
Method 4: Using Python with openpyxl
Python’s openpyxl library can read and write Excel files. Here’s a simple script to merge them:
import os from openpyxl import load_workbook def merge_excel_files(path, output_filename): writer = load_workbook(os.path.join(path, output_filename)) writer_wb = writer.active for file in os.listdir(path): if file.endswith('.xlsx') and file != output_filename: workbook = load_workbook(os.path.join(path, file)) for sheet in workbook.worksheets: for row in sheet.iter_rows(values_only=True): writer_wb.append(row) writer.save(output_filename) merge_excel_files('C:\Excel Files', 'merged.xlsx')
Method 5: VBA Macro
If you prefer a solution integrated directly within Excel, VBA macros can merge files:
Sub MergeExcelFiles() Dim FolderPath As String, FilePath As String, FileName As String, Sheet As Worksheet Dim NextRow As Long Dim MergeObj As Object, SourceWb As Workbook FolderPath = "C:\Excel Files\" FileName = Dir(FolderPath & "*.xlsx") ' Open the workbook to merge into Set MergeObj = CreateObject("Scripting.FileSystemObject") Set SourceWb = Workbooks.Open(FolderPath & FileName) ' Loop through all Excel files in the folder FileName = Dir(FolderPath & "*.xlsx") Do While FileName <> "" If FileName <> ThisWorkbook.Name Then ' Open the source workbook With Workbooks.Open(FolderPath & FileName) For Each Sheet In .Worksheets ' Find the last row in the target workbook NextRow = ThisWorkbook.Sheets(1).Cells(ThisWorkbook.Sheets(1).Rows.Count, "A").End(xlUp).Row + 1 ' Copy data from the source sheet to the target Sheet.UsedRange.Copy Destination:=ThisWorkbook.Sheets(1).Cells(NextRow, 1) Next Sheet End With End If FileName = Dir Loop SourceWb.Close False Set MergeObj = Nothing MsgBox "Merge Complete" End Sub
📝 Note: Ensure all Excel files are closed before running the batch file or PowerShell script to avoid conflicts or errors.
Merging Excel files using CMD can save you significant time and effort, especially when dealing with large datasets or numerous reports. Whether through batch scripting, PowerShell, Python, Power Automate, or VBA, each method offers a different level of customization and complexity, tailored to meet various needs. Each approach has its own merits, from the simplicity of batch files for straightforward tasks to the power of Python scripts for intricate data manipulation. By integrating these tools into your workflow, you can automate repetitive tasks, reduce errors, and increase efficiency. Remember to adjust paths and filenames according to your system configuration, and always back up your data before attempting automation to safeguard against any potential data loss or corruption. Automation in Excel isn’t just about merging files; it's about transforming the way you work with data, allowing for scalability, consistency, and error reduction in your daily tasks.
Can I merge Excel files with different formats?
+
Yes, you can merge files in various formats like .xlsx, .xlsm, or .xls, but ensure the script or method you use is compatible with all file types.
How do I ensure data integrity when merging files?
+
Always back up your original files before merging. Check scripts or macros for data handling compatibility to prevent loss or corruption. Use test files to validate results.
What are the limitations when using these methods?
+
Limitations include memory constraints for large datasets, compatibility issues with different Excel versions, and the potential for formatting or content issues if the files are not uniform in structure.