Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find latest file creation date in folder 1

Status
Not open for further replies.

MikeCDPQ

Technical User
Sep 11, 2003
173
CA
I would like to find the name of the file with the most recent creation date in a given folder.

I grabbed this code on this site which takes me a step closer but I am still missing something. How do I get the max date out of that.

Here's the code:

Dim oFSO As Object, oFolder As Object, oFile As Object
Dim sPath As String

sPath = "G:\my path\"

Set oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FolderExists(sPath) Then
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
If LCase$(Right$(oFile.Name, 4)) = ".xls" Then
Debug.Print oFile.Name, oFile.DateCreated
End If
Next oFile


Set oFolder = Nothing
Else
msgbox "Cannot find " & sPath
End If
Set oFSO = Nothing

Thanks for any help.

Mike
 
Put it in the sorted listbox (hidden) and retrieve the last or the first item
 
Or modify your code to

Code:
    Dim oFSO As Object, oFolder As Object, oFile As Object
    Dim sPath As String
    Dim HoldName As String
    Dim HoldDate As Date
    
    sPath = "C:\"
    
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    If oFSO.FolderExists(sPath) Then
        Set oFolder = oFSO.getfolder(sPath)
        For Each oFile In oFolder.Files
            If LCase$(Right(oFile.Name, 4)) = ".xls" Then
[b]                If oFile.datecreated > HoldDate Then
                    HoldDate = oFile.datecreated
                    HoldName = oFile.Name
                End If
            End If
[/b]
        Next
        
        Debug.Print HoldName, HoldDate
    Else
        MsgBox "Cannot find " & sPath
    End If
 
Thanks bjd4jc

It works beautifully.

You're a life saver :)

Thanks a bunch !

Mike
 
if the file is a text file how can i open the individual text file to read the content
 
Dim FileStream as TextStream
Dim FileContents as String

Code:
If LCase$(Right(oFile.Name, 4)) = ".txt" Then
    Set FileStream = oFSO.OpenTextFile(ofile.Path)
    FileContents = FileStream.ReadAll
End If
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top