Sub LoopFiles()
'https://www.mrexcel.com/board/threads/vba-multiple-excel-files-and-need-a-particular-range-of-data-with-the-same-format.1210177/
Set fso = CreateObject("Scripting.FileSystemObject")
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
Dim wb As Workbook
Set wb = ThisWorkbook
On Error GoTo OnErr
Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
'Optional: FileDialog properties
fDialog.AllowMultiSelect = True
fDialog.Title = "Select files"
fDialog.InitialFileName = "C:\"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Custom Excel Files", "*.xlsx, *.xlsm, *.xls, *.csv"
fDialog.Filters.Add "All files", "*.*"
'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
'loop through each file
For Each it In fDialog.SelectedItems
'get the filename to make a new tab
SourceName = fso.GetBaseName(it)
'check to see if this tabname exists
For i = 1 To ThisWorkbook.Worksheets.Count
'if the tabname exists
If wb.Sheets(i).Name = SourceName Then
'if it does, set a counter and go to then next file
Count = 1
Exit For
End If
Next i
'if the name doesn't exist
If Count = 0 Then
'create a new worksheet with the filename
wb.Sheets.Add.Name = SourceName
'open a hidden instance of Excel
Dim app As New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
'open the latest workbook
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(it)
'with the latest workbook, Overall Results worksheet
With book.Worksheets("Overall Results")
'copy A1:D60
.Range("A1:D60").SpecialCells(xlCellTypeVisible).Copy
'paste it into this workbook in the latest worksheet, cell A1
wb.Worksheets(SourceName).Range("A1").PasteSpecial xlPasteValues
'this next copy/paste is to reduce the clipboard down to a smaller size
'so Excel won't ask if you want to save it on exit.
.Range("A1").SpecialCells(xlCellTypeVisible).Copy
wb.Worksheets(SourceName).Range("A1").PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
Else
'put the name in an array
DupWS = DupWS & Chr(10) & SourceName
'reset the count
Count = 0
End If
Next
Else
'if the cancel button is selected
End
End If
'if there are duplicates, show what was skipped.
If Len(DupWS) > 0 Then
x = MsgBox("These Worksheets already exist in" & vbCrLf & "this workbook and were not imported:" & DupWS, vbExclamation)
End If
End
OnErr:
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
x = MsgBox("Error: " & Err & Chr(10) & Err.Description, vbCritical)
End Sub