I am trying to write a code that opens the most recent file in a folder and copy data from it. I am having trouble setting it as a source for the copying without the specific file name. I do not want to set a file name as I just want it to take the most recent file and copy it.
I was able to get it to open the most recent file, but it is getting stuck on source data. My goal is to not have to manually select a file every time a newer one comes out.
Sub CopyDataFromCSVFiles()
Dim SourceFolder As String
Dim MasterWorkbook As Workbook
Dim CurrentData As Workbook
Dim DataSheet As Worksheet
Dim MasterSheet As Worksheet
Dim CSVFile As String
Dim NextRow As Long
Dim FileExtension As String
' Set the source folder containing CSV files
SourceFolder = "P:\Fluid Products Engineering\EOP Tester Data\Combination Program\Raw Data\"
' Set the master workbook (file picker dialog)
Set MasterWorkbook = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls; *.xlsx; *.xlsm), *.xls; *.xlsx; *.xlsm", Title:="Please select the master workbook")
If MasterWorkbook = "False" Then
MsgBox "No master workbook selected. Exiting..."
Exit Sub
Else
Set MasterWorkbook = Workbooks.Open(MasterWorkbook)
End If
' Set master worksheet
Set MasterSheet = MasterWorkbook.Sheets(1)
' Loop through each file in the folder
CSVFile = Dir(SourceFolder & "*.csv")
Do While CSVFile <> ""
' Open current CSV file
Set CurrentData = Workbooks.Open(SourceFolder & CSVFile)
' Set current data worksheet
Set DataSheet = CurrentData.Sheets(1)
' Determine the next available row in master workbook
NextRow = MasterSheet.Cells(MasterSheet.Rows.Count, "A").End(xlUp).Row + 1
' Copy data from current CSV file to master workbook
DataSheet.UsedRange.Copy MasterSheet.Cells(NextRow, 1)
' Close current CSV file without saving changes
CurrentData.Close False
' Get next CSV file
CSVFile = Dir
Loop
' Close master workbook with saving changes
MasterWorkbook.Close True
MsgBox "Data has been successfully copied to the master workbook.", vbInformation
End Sub
Copy From One Closed Workbook to Another (
PERSONAL.xlsb!?)