Find the latest saved file

I would like to find the latest saved file in directory c:\test\ and compare if the same file exist in directory c:\test\old\.
Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Create a new project and add two textboxes and a commandbutton.



' ************************* Code for Form1 *************************
Option Explicit

Private Sub Form_Load()
    Text1.Text = "c:\test\"
    Text2.Text = "c:\test\old\"
    Command1.Caption = "Check Files"
End Sub

Private Sub Command1_Click()
    Dim newestFile As String
    Dim newestDate As Date
    Dim curDate As Date
    Dim files As Collection
    Dim file As Variant
    Set files = getFilesInDirectory(Text1.Text, "*")
    If files.Count > 0 Then
        newestFile = files.Item(1)
        newestDate = FileDateTime(newestFile)
        For Each file In files
            curDate = FileDateTime(file)
            If curDate > newestDate Then
                newestDate = curDate
                newestFile = file
            End If
        Next file
        If Dir(Text2.Text, vbDirectory) <> "" Then
            If Right(Text2.Text, 1) <> "\" Then
                Text2.Text = Text2.Text & "\"
            End If
            If Dir(Text2.Text & newestFile) <> "" Then
                MsgBox "File: """ & newestFile & """ Exists in """ & Text2.Text & """"
                MsgBox "File: """ & newestFile & """ Does Not Exist in """ & Text2.Text & """"
            End If
            MsgBox "Target Directory does not exist"
        End If
        MsgBox "Directory is Empty"
    End If
End Sub

Private Function getFilesInDirectory(targetDirectory As String, filePattern As String) As Collection
    Dim fileCollection As Collection
    Dim curFile As String
    On Error GoTo noSuchDirectory
    Set fileCollection = New Collection
    ChDir targetDirectory
    On Error GoTo 0
    curFile = Dir(filePattern)
    Do Until curFile = ""
        fileCollection.Add curFile, curFile
        curFile = Dir()
    Set getFilesInDirectory = fileCollection
    Exit Function
    MsgBox "Invalid Directory: " & targetDirectory
    Set getFilesInDirectory = fileCollection
End Function
mikael_luAuthor Commented:
Hi Idle_Mind!

Thanks for a very fine solution of my problem, I'm very happy.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.