VBA Code to Merge Multiple Excel Workbooks
There's some great VBA code posted to Experts Exchange by Professor JimJam which you can use merge multiple Excel workbooks.
Note the line in the code where you need to specify the range that you are collecting:
Sub MergeTest()
Dim SummarySheet As Worksheet Dim FolderPath As String Dim SelectedFiles() As Variant Dim NRow As Long Dim FileName As String Dim NFile As Long Dim WorkBk As Workbook Dim SourceRange As Range Dim DestRange As Range Dim LastRow As Long
' Create a new workbook and set a variable to the first sheet. Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Open the file dialog box and filter on Excel files, allowing multiple files ' to be selected. SelectedFiles = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
' NRow keeps track of where to insert new rows in the destination workbook. NRow = 1
' Loop through the list of returned file names For NFile = LBound(SelectedFiles) To UBound(SelectedFiles) ' Set FileName to be the current workbook file name to open. FileName = SelectedFiles(NFile)
' Open the current workbook. Set WorkBk = Workbooks.Open(FileName)
' Get row number of last used row LastRow = WorkBk.Worksheets(1).Cells.Find(What:="*", _ After:=WorkBk.Worksheets(1).Cells.Range("A1"), _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows).Row
' Set the cell in column N to be the file name. SummarySheet.Range("N" & NRow).Value = FileName ' Create header row Set SourceRange = WorkBk.Worksheets(1).Range("A1:M1") Set DestRange = SummarySheet.Range("A1:M1") DestRange.Value = SourceRange.Value
' Set the source range to be B1 through M?. ' Modify this range for your workbooks. It can span multiple rows. Set SourceRange = WorkBk.Worksheets(1).Range("A2:M" & LastRow)
' Set the destination range to start at column A and be the same size as the source range. Set DestRange = SummarySheet.Range("A" & NRow) Set DestRange = DestRange.Resize(SourceRange.Rows.Count, SourceRange.Columns.Count)
' Copy over the values from the source to the destination. DestRange.Value = SourceRange.Value
' Increase NRow so that we know where to copy data next. NRow = NRow + DestRange.Rows.Count
' Close the source workbook without saving changes. WorkBk.Close savechanges:=False Next NFile
' Call AutoFit on the destination sheet so that all data is readable. SummarySheet.Columns.AutoFit End Sub
Play the macro, and it will prompt you to select the workbooks you want to merge. So from files like these:
. . . is generated a workbook like this, combining the content of all four: