SortedFiles

Get a sorted list of files in a directory using the File System Object (FSO) and Quick sort
Keywords directory, dir, sorted, quick sort, File System Object, FSO
Categories Algorithms, Files and Directories

Make a new File System Object. Use it to get a Folder object representing the directory of interest. Use that object's Files collection to get the file names.
Then sort the names using Quick sort.

' Return an array containing the names of the files in the directory sorted alphabetically.


Public

Not Tested

Not My Work

Private Function SortedFiles(ByVal dir_path As String, _
Optional ByVal exclude_self As Boolean = True, Optional _
ByVal exclude_parent As Boolean = True) As String()
Dim fso As FileSystemObject
Dim fso_folder As Folder
Dim txt As String
Dim fso_file As File
Dim i As Long
Dim file_names() As String

' Make a new File System object.
Set fso = New FileSystemObject

' Get the FSO Folder (directory) object.
Set fso_folder = fso.GetFolder(dir_path)

' Make the list of names.
ReDim file_names(1 To fso_folder.Files.Count)
i = 1
For Each fso_file In fso_folder.Files
file_names(i) = fso_file.Name
i = i + 1
Next fso_file

' Sort the list of files.
Quicksort file_names, 1, fso_folder.Files.Count

' Return the sorted list.
SortedFiles = file_names
End Function

' Use Quicksort to sort a list of strings.
'
' This code is from the book "Ready-to-Run Visual Basic Algorithms" by Rod Stephens.
' http://www.vb-helper.com/vba.htm
Private Sub Quicksort(list() As String, ByVal min As Long, _
ByVal max As Long)
Dim mid_value As String
Dim hi As Long
Dim lo As Long
Dim i As Long

' If there is 0 or 1 item in the list, this sublist is sorted.
If min >= max Then Exit Sub

' Pick a dividing value.
i = Int((max - min + 1) * Rnd + min)
mid_value = list(i)

' Swap the dividing value to the front.
list(i) = list(min)

lo = min
hi = max
Do
' Look down from hi for a value < mid_value.
Do While list(hi) >= mid_value
hi = hi - 1
If hi <= lo Then Exit Do
Loop
If hi <= lo Then
list(lo) = mid_value
Exit Do
End If

' Swap the lo and hi values.
list(lo) = list(hi)

' Look up from lo for a value >= mid_value.
lo = lo + 1
Do While list(lo) < mid_value
lo = lo + 1
If lo >= hi Then Exit Do
Loop
If lo >= hi Then
lo = hi
list(hi) = mid_value
Exit Do
End If

' Swap the lo and hi values.
list(hi) = list(lo)
Loop

' Sort the two sublists.
Quicksort list, min, lo - 1
Quicksort list, lo + 1, max
End Sub


ByVal dir_path As String, Optional ByVal exclude_self As Boolean = True, Optional ByVal exclude_parent As Boolean = True

Views 197 Downloads 70

VB6 File System
ANmarAmdeen
763
Attachments
Revisions

v1.0

Needs