Eileen has attended:
Excel VBA Advanced course
Excel filename wildcard digits
Hi,
We are trying to code a macro that opens the latest file in a folder with a specified filename in this format:
YTD_250412 at 1108.xlsx
where the 250412 and the 1108 change from file to file:
YTD_###### at ####.xlsx
We don't want a file called YTD_250412 at 1108 any other details.xlsx to be opend.
Is there any way of coding in for this, this is what we have so far?
'Sub latestfile()
'
'Dim strCurrentFile As String
'Dim datCurrentFileDate As Date
'Dim strLatestFile As String
'Dim datLatestFileDate As Date
'
'strCurrentFile = Dir("C:\temp\YTD_*" & " at " & "*.xlsx")' Do While strCurrentFile <> ""
' datCurrentFileDate = filedatetime("c:\temp\" & strCurrentFile)
' If datCurrentFileDate > datLatestFileDate Then
' strLatestFile = strCurrentFile
' datLatestFileDate = datCurrentFileDate
' End If
' strCurrentFile = Dir
' Loop
'
' MsgBox "Most recent file: " & strLatestFile & vbCr _
'
'End Sub
This will work but we don't want to specify the date & time:
'strCurrentFile = Dir("C:\temp\YTD_" & "250412" & " at " & "1108" & ".xlsx")
We tried this also but it wont work:
'strCurrentFile = Dir("C:\temp\YTD_" & "[0-9][0-9][0-9][0-9][0-9][0-9]" & " at " & "[0-9][0-9][0-9][0-9]" & ".xlsx")
Any advice?
Eileen.
RE: Excel filename wildcard digits
Hi Eileen, thanks for your query. On your advanced Excel VBA course you will have covered arrays. I would loop through the folder of files extracting (using MID, probably) the date and time of each file and add it to an array.
Then I would loop through the array and find the latest date and time. I would pass those values to two other variables.
I would then concatenate those variables into a filename string and finally open only that file.
Hope this helps,
Anthony