Hello, I got nice help with Macro which I am using at my work.
Now I come up to more complicated thing
I have a basic path C:\GENERAL\PLAN\Delivery Plan\Delivery Plans\current year\current month with format 08 August\after WC and date based on Sunday of previous week so in my case WC 13 08 2023(can be latest folder created)\delivery day like Friday (can be latest folder created\
I have current code, but I don't know how to add there option to detect latest folders in Month and in WC
Now I come up to more complicated thing
I have a basic path C:\GENERAL\PLAN\Delivery Plan\Delivery Plans\current year\current month with format 08 August\after WC and date based on Sunday of previous week so in my case WC 13 08 2023(can be latest folder created)\delivery day like Friday (can be latest folder created\
I have current code, but I don't know how to add there option to detect latest folders in Month and in WC
VBA Code:
Public Sub OpenTP()
Dim basePath As String, fullPath As String
Dim yearMonth As String
Dim workbookFileName As String
basePath = "C:\GENERAL\PLAN\Delivery Plan\Delivery Plans\"
'Current year and month
yearMonth = Format(Date, "yyyy\\mm mmmm\\")
fullPath = basePath & yearMonth
If Dir(fullPath, vbDirectory) = vbNullString Or Dir(fullPath & "Final DP*.xlsx") = vbNullString Then
'Path doesn't exist or doesn't contain Handover*.xlsm, so construct path for previous month (and year)
yearMonth = Format(DateAdd("m", -1, Date), "yyyy\\mm mmmm\\")
fullPath = basePath & yearMonth
End If
workbookFileName = Find_Latest_File(fullPath, "Final DP*.xlsx")
If workbookFileName <> "" Then
Workbooks.Open workbookFileName
End If
End Sub
VBA Code:
Private Function Find_Latest_File(ByVal folder As String, Optional matchFiles As String = "*.*") As String
Dim fileName As String
Dim fileTime As Date, latestTime As Date
If Right(folder, 1) <> "\" Then folder = folder & "\"
Find_Latest_File = ""
fileTime = 0
fileName = Dir(folder & matchFiles)
While fileName <> vbNullString
fileTime = FileDateTime(folder & fileName)
If fileTime > latestTime Then
Find_Latest_File = folder & fileName
latestTime = fileTime
End If
fileName = Dir
Wend