List files by date
By: Lorenzo Dalla Vecchia Date: 23/06/2000

Visual Basic does not include an "Explorer" control to list files: the only resource is the Dir function.
The following code, that makes use of the
Dir function and of a couple of arrays, fills a listbox (lstFiles) with all the files in a directory, sorted by date.

Dim DirPath As String
Dim Pattern As String
Dim FileName As String
Dim Unsorted() As String
Dim Sorted() As String
Dim Max As Date
Dim MaxN As Integer
Dim a As Integer
Dim b As Integer

'Define the target of search

DirPath = "C:\"       'must end with backslash!
Pattern = "*.*"       'search criteria all files must meet

ReDim Unsorted(0)

'Search for files
FileName = Dir(DirPath & Pattern)
    If FileName = "" Then Exit Do
    If FileName <> "." And FileName <> ".." Then

        'Add valid file to unsorted array
        ReDim Preserve Unsorted(UBound(Unsorted) + 1)
        Unsorted(UBound(Unsorted)) = FileName
    End If
    FileName = Dir()

ReDim Sorted(UBound(Unsorted))

'Now sort the array by date

For a = 1 To UBound(Sorted)
    Max = 0
    MaxN = -1
    For b = 1 To UBound(Unsorted)
        If Unsorted(b) <> "" Then
            If FileDateTime(DirPath & Unsorted(b)) > Max Then
                Max = FileDateTime(DirPath & Unsorted(b))
                MaxN = b
            End If
        End If
    Next b
    Sorted(a) = Unsorted(MaxN)
    Unsorted(MaxN) = ""
Next a

'Fill the listbox with the sorted array

For a = 1 To UBound(Sorted)
    lstFiles.AddItem Sorted(a)
Next a

The most recent files will be on the top, the oldest on the bottom.
You may like to change the search path, search criteria and listbox name.

Click Here!

Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: