View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
joel joel is offline
external usenet poster
 
Posts: 9,101
Default Open most recent file

Try this code. FILESEARCH doesn't work in excel 2007. This method will work
in all excel versions. Yu need to modify FilePath below as required.


Sub GetLatestFile()

Const FilePath = "Mypath"


Set fso = CreateObject _
("Scripting.FileSystemObject")

Set folder = _
fso.GetFolder(FilePath)

MyDate = 1
Myfile = ""
For Each fl In folder.Files
PeriodPos = InStrRev(fl.Name, ".")
EXT = Mid(fl.Name, PeriodPos + 1)
If UCase(EXT) = "JNK" Then
If fl.DateLastModified MyDate Then
Myfile = fl.Path
MyDate = fl.DateLastModified
End If
End If
Next fl
If Myfile = "" Then
MsgBox "There were no files found."
Else
MsgBox "The newest file is " & Myfile & _
" created " & MyDate

Workbooks.Open Myfile
End If

End Sub


"Sandy" wrote:

Hello
I am trying to open the most recent file in a folder. I have found 2
possible solutions here but neither seem to work for me.

First:
Const FilePath = "Mypath"
Workbooks.Open Filename:=FindNewestFile(FilePath)

This one gives me Undefined sub or function on
FindNewestFile

The other:

With Application.FileSearch
.NewSearch
.LookIn = "C:\"
.Filename = "*.jnk"
.Execute SortBy:=msoSortBySize
.NewSearch
.LookIn = "mypath"
.SearchSubFolders = False
.FileType = msoFileTypeExcelWorkbooks
If .Execute(SortBy:=msoSortByLastModified,
SortOrder:=msoSortOrderDescending) 0 Then
MsgBox "The newest file is " & .FoundFiles(1) & " created " &
FileDateTime(.FoundFiles(1))
Workbooks.Open .FoundFiles(1)
Else
MsgBox "There were no files found."
End If
End With

This one gives me "Object doesn't support this action" on
With Application.FileSearch

Can anyone help?
Thanks!