The macro merges all the data from excel files in the specific folder into the sheet named Master.
The data extends from Col. A to Col.Y.
The requirement is
The filename( excluding extension, .xls, .xlsx, .xlsm etc) to be included in Col.Z for each entry from the particular file.
The data extends from Col. A to Col.Y.
Code:
Sub Button1_Click()
'Summary: Merge files in a specific folder into one master sheet (stacked)
' Moves imported files into another folder
Dim fName As String, fPath As String, fPathDone As String
Dim LR As Long, NR As Long
Dim wbData As Workbook, wsMaster As Worksheet
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set wsMaster = ThisWorkbook.Sheets("Master") 'sheet report is built into
With wsMaster
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
.UsedRange.Offset(1).EntireRow.Clear
NR = 2
Else
NR = .Range("a" & .Rows.Count).End(xlUp).Row + 1
End If
MsgBox "Please select a folder with files to consolidate"
Do
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "C:\2010\Test\"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
fPath = .SelectedItems(1) & "\"
Exit Do
Else
If MsgBox("No folder chose, do you wish to abort?", _
vbYesNo) = vbYes Then Exit Sub
End If
End With
Loop
fPathDone = fPath & "Imported\"
On Error Resume Next
MkDir fPathDone
On Error GoTo 0
fName = Dir(fPath & "*.xls*")
'Import a sheet from found files
Do While Len(fName) > 0
If fName <> ThisWorkbook.Name Then 'don't reopen this file accidentally
Set wbData = Workbooks.Open(fPath & fName) 'Open file
'This is the section to customize, replace with your own action code as needed
LR = Range("A" & Rows.Count).End(xlUp).Row 'Find last row
Range("A1:A" & LR).EntireRow.Copy .Range("A" & NR)
wbData.Close False 'close file
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'Next row
Name fPath & fName As fPathDone & fName 'move file to IMPORTED folder
End If
fName = Dir 'ready next filename
Loop
End With
ErrorExit: 'Cleanup
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
The requirement is
The filename( excluding extension, .xls, .xlsx, .xlsm etc) to be included in Col.Z for each entry from the particular file.