Find latest file in folder & Open
Hi all, i would like to find the latest file in a folder and open it with
code. The files would have different names as they are updates with a code on the end. Could somebody help me with this please. -- Les |
Find latest file in folder & Open
Try this:
Sub AAAAA() Const FilePath = "D:\Data\" Workbooks.Open Filename:=FindNewestFile(FilePath) End Sub Function FindNewestFile(FilePath As String) As String Dim LastDate As Date, NewDate As Date Dim LastFile As String, NewFile As String 'Check all the .XLS files in the folder. Find the 'most recent file. LastFile$ = LCase$(Dir(FilePath$ & "*.XLS")) LastDate = FileDateTime(FilePath$ & LastFile$) NewFile$ = LastFile$ Do While Len(NewFile$) 0 NewFile$ = LCase$(Dir()) If Len(NewFile$) = 0 Then Exit Do NewDate = FileDateTime(FilePath$ & NewFile$) If NewDate LastDate Then LastDate = NewDate LastFile$ = NewFile$ End If Loop FindNewestFile$ = FilePath$ & LastFile$ End Function Hope this helps, Hutch "Les" wrote: Hi all, i would like to find the latest file in a folder and open it with code. The files would have different names as they are updates with a code on the end. Could somebody help me with this please. -- Les |
Find latest file in folder & Open
Thanks Tom
-- Les "Tom Hutchins" wrote: Try this: Sub AAAAA() Const FilePath = "D:\Data\" Workbooks.Open Filename:=FindNewestFile(FilePath) End Sub Function FindNewestFile(FilePath As String) As String Dim LastDate As Date, NewDate As Date Dim LastFile As String, NewFile As String 'Check all the .XLS files in the folder. Find the 'most recent file. LastFile$ = LCase$(Dir(FilePath$ & "*.XLS")) LastDate = FileDateTime(FilePath$ & LastFile$) NewFile$ = LastFile$ Do While Len(NewFile$) 0 NewFile$ = LCase$(Dir()) If Len(NewFile$) = 0 Then Exit Do NewDate = FileDateTime(FilePath$ & NewFile$) If NewDate LastDate Then LastDate = NewDate LastFile$ = NewFile$ End If Loop FindNewestFile$ = FilePath$ & LastFile$ End Function Hope this helps, Hutch "Les" wrote: Hi all, i would like to find the latest file in a folder and open it with code. The files would have different names as they are updates with a code on the end. Could somebody help me with this please. -- Les |
All times are GMT +1. The time now is 06:40 PM. |
Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com