Here you Go:
This one will delete the old data every time you run the macro
I added some hints so you can know how it works
Option Explicit
Option Base 1
Sub CollectWorkbooks()
Dim varFiles As Variant
varFiles = Application.GetOpenFilename("Excel-files,*.xls; *.xlsx; *.xlsm", _
1, "Select Workbooks to Collect", , True)
'checking if no files were selected
On Error Resume Next
If UBound(varFiles) = 0 Then
End If
If Err.Number = 13 Then Exit Sub
On Error GoTo 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim n As Long, r As Long
Dim f As Integer, s As Integer
Dim wbSource As Workbook, wbMaster As Workbook
Dim shSource As Worksheet, shDest As Worksheet
Dim chkFIRST As Boolean
Set wbMaster = ThisWorkbook
'deleteing old sheets from the master file except the first one
Do While wbMaster.Sheets.Count > 1
wbMaster.ActiveSheet.Delete
Loop
'deleting records from the first sheet
Set shDest = ThisWorkbook.Worksheets(1)
r = shDest.Cells.SpecialCells(xlCellTypeLastCell).Row
shDest.Range(1 & ":" & r).ClearContents
'opening each file and importing the data
chkFIRST = True
For f = 1 To UBound(varFiles)
Set wbSource = Workbooks.Open(varFiles(f), ReadOnly:=True)
For Each shSource In wbSource.Worksheets
'renaming the first sheet in the master file to the name of the first sheet in the first source file
If chkFIRST = True Then
shDest.Name = shSource.Name
chkFIRST = False
End If
'getting the same sheet in the master file if it exists
Set shDest = Nothing
On Error Resume Next
Set shDest = wbMaster.Worksheets(shSource.Name)
r = shDest.Cells.SpecialCells(xlCellTypeLastCell).Row
On Error GoTo 0
'if the sheet doesnt exist then create it
If shDest Is Nothing Then
Err.Clear
Set shDest = wbMaster.Worksheets.Add(after:=wbMaster.Worksheets(wbMaster.Worksheets.Count))
shDest.Name = shSource.Name
r = 1
End If
'adding the records
r = r + 1
n = shSource.Cells.SpecialCells(xlCellTypeLastCell).Row
s = shSource.Cells.SpecialCells(xlCellTypeLastCell).Column
shSource.Range(shSource.Cells(2, 1).Address & ":" & shSource.Cells(n, s).Address).Copy _
Destination:=shDest.Range(shDest.Cells(r, 1).Address & ":" & shDest.Cells(r + n, s).Address)
Next
wbSource.Close
Next
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Bookmarks