I'm using this macro to merge all xls files in a folder to a single sheet master file.
I want to append the Filename in the end column in the Master File so that I exactly know which file that data came from.
Experts please help!
I want to append the Filename in the end column in the Master File so that I exactly know which file that data came from.
Experts please help!
Code:
'Description: Combines all files 1st sheet in a folder to a master file
Sub MergeFilesWithoutSpaces()
Dim path As String, ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
ThisWB = ActiveWorkbook.Name
path = GetDirectory("Select a folder containing Excel files you want to merge")
RowofCopySheet = InputBox("Enter Row to start copy on") ' Row to start on in the sheets you are copying from
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets(1)
Filename = Dir(path & "\*.xls", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.Count, 1).End(xlUp).Row, Cells(1, Columns.Count).End(xlToLeft).Column))
Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.Count, 1).End(xlUp).Row + 1)
CopyRng.Copy
Dest.PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False 'Clear Clipboard
Wkb.Close False
End If
Filename = Dir()
Loop
Range("A1").Select
Columns.AutoFit
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub