Sub MergeFiles()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim fso As Object, fol As Object, fil As Object
Dim lr As Long
Dim wbi As Workbook, wsi As Worksheet, wso As Worksheet
Dim filname As String, shName As String, filext As String, filPath As String
Set folder = Application.FileDialog(msoFileDialogFolderPicker) 'Choose parent folder
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
Set fso = CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder(xDir)
For Each fil In fol.Files 'loop through files in folder
filext = fso.GetExtensioNname(fil)
If filext Like "xls*" Then 'check that file is excel file
filname = fso.GetBaseName(fil)
If filname Like "*-*" Then 'check file name include '-'
shName = Trim(Right(filname, Len(filname) - InStr(filname, "-"))) 'split name after '-'
filPath = fso.GetAbsolutePathName(fil) 'file path
Set wbi = Workbooks.Open(fso.GetAbsolutePathName(filPath)) ' open file
Set wsi = wbi.Sheets(1)
If FindSheet(shName) Is Nothing Then 'check that sheet has same name as file exist or not
Set wso = ThisWorkbook.Sheets.Add(after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)) 'if sheet not exist then create new sheet
wso.Name = shName 'rename sheet
Else
Set wso = FindSheet(shName) 'if sheet existed
End If
If wso.UsedRange.Rows.count = 1 Then
lr = 1
wsi.UsedRange.Copy Destination:=wso.Cells(lr, 1) 'get data and paste to sheet
Else
lr = wso.UsedRange.Rows.count + 1
Intersect(wsi.UsedRange, wsi.UsedRange.Offset(2)).Copy Destination:=wso.Cells(lr, 1) 'get data and paste to sheet
End If
wbi.Close (False)
End If
End If
Next fil
Set fil = Nothing
Set fol = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function FindSheet(ByVal shName As String) As Worksheet 'find match worksheet
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
If ws.Name = shName Then
Set FindSheet = ws
Exit For
End If
Next ws
End Function