I am new on doing the VBA codes. So not familiar with coding as such. Just copied few code snippets. However, not getting the desired output.
What I have done need is looped through excel files in a folder and pasted the desired data from the worksheets into the master worksheet.
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim lRow As Long
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim y As Workbook
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "C:\Users\check"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
Set y = Workbooks.Open("C:\Users\Super\Desktop\Master")
Set ws2 = y.Sheets("Conso P-L")
Set ws3 = y.Sheets("Conso Expenses")
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
With wb.Sheets("Profit-Loss")
lRow = .Range("A" & Rows.Count).End(xlUp).Row
.Range("A2:M" & lRow).Copy ws2.Range("A" & Rows.Count).End(xlUp)(2)
End With
Application.CutCopyMode = False
With wb.Sheets("Expenses")
lRow = .Range("A" & Rows.Count).End(xlUp).Row
.Range("A2:M" & lRow).Copy ws3.Range("A" & Rows.Count).End(xlUp)(2)
End With
Application.CutCopyMode = False
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
However, the problem is I need to add a column in the master worksheets to get the filenames of the source data (excluding the .xls or .xlsx), I am not able to figure out where to tweak the code!!
Added a screenshot below for the desired output I require. the filename is required in Column A of both the worksheets of the master workbook.
Appreciate if anybody can help please..