I have tried to write code to limit files to see in folder C::\Extract and secondly they must be todays date (Date Modified) format is dd/mm/yyyy
The rest of the code works 100%
Kindly amend my code as I cannot get it to limit the selection to only show only files containing "Parts" in the file name of the csv files and date modified ,being todays date
The rest of the code works 100%
Kindly amend my code as I cannot get it to limit the selection to only show only files containing "Parts" in the file name of the csv files and date modified ,being todays date
Code:
Sub Open_Workbook()
Dim nb As Workbook, tw As Workbook, WS As Worksheet, LR As Long, A As Variant
Dim rngDestination As Range
Dim filename As Variant
Dim fileDir As String
Dim fileItem As String
Dim fileDate As Date
Dim fileDateFormat As String
Dim latestFiles As Collection
Dim dlg As FileDialog
Dim i As Integer
Set WS = ThisWorkbook.Sheets("Imported Data")
WS.UsedRange.ClearContents
On Error Resume Next
Set rngDestination = WS.Range("A1")
On Error GoTo 0
If rngDestination Is Nothing Then Exit Sub 'User canceled
fileDir = "C:\Extract\"
Set latestFiles = New Collection
fileDateFormat = Format(Date, "dd-mm-yyyy") ' Format as "dd-mm-yyyy" or "dd/mm/yyyy" depending on your system's settings
' Loop through all files in the directory
fileItem = Dir(fileDir & "*Parts*.csv")
Do While fileItem <> ""
' Check if the file is last modified today
fileDate = FileDateTime(fileDir & fileItem)
If Format(fileDate, "dd-mm-yyyy") = fileDateFormat Then
' Add the file to the collection if it matches the criteria
latestFiles.Add fileDir & fileItem
End If
fileItem = Dir
Loop
' If matching files are found, display the FileDialog for user to select
If latestFiles.Count > 0 Then
' Use the FileDialog to show only matching files
Set dlg = Application.FileDialog(msoFileDialogFilePicker)
With dlg
.Title = "Select CSV file"
.ButtonName = "Open"
.AllowMultiSelect = False
.InitialFileName = fileDir & "*.csv"
.Filters.Clear
.Filters.Add "CSV Files with 'Parts' in Name", "*.csv"
If .Show = -1 Then ' If the user selects a file
' Verify that the selected file matches the filter criteria
filename = .SelectedItems(1)
If InStr(1, filename, "Parts", vbTextCompare) > 0 And Format(FileDateTime(filename), "dd-mm-yyyy") = fileDateFormat Then
Application.ScreenUpdating = False
Dim srcWorkbook As Workbook
Set srcWorkbook = Workbooks.Open(filename:=filename, local:=True)
ThisWorkbook.Activate
srcWorkbook.Sheets(1).Range("A:AM").Copy
rngDestination.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
srcWorkbook.Close SaveChanges:=False
Application.ScreenUpdating = True
Else
MsgBox "Selected file does not match the criteria.", vbExclamation
End If
Else
MsgBox "No file was selected.", vbExclamation
End If
End With
Else
MsgBox "No files matching the criteria found.", vbExclamation
End If
End Sub