Home > How-To Library > File/Folders Handling

How to Load the names of all executable files in a directory tree into a ListBox.

**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * ****************************************************************
'Note: this is a recursive routine. Sub ListExecutableFiles(ByVal path As String, lst As ListBox) Dim names() As String, i As Long, j As Integer ' Ensure that there is a trailing backslash. If Right(path, 1) <> "\" Then path = path & "\" ' Get the list of executable files. For j = 1 To 3 ' At each iteration search for a different extension. names() = GetFiles(path & "*." & Choose(j, "exe", "bat", "com")) ' Load partial results in the ListBox lst. For i = 1 To UBound(names) lst.AddItem path & names(i) Next Next ' Get the list of subdirectories, including hidden ones, ' and call this routine recursively on all of them. names() = GetDirectories(path, vbHidden) For i = 1 To UBound(names) ListExecutableFiles path & names(i), lst Next End Sub Public Function GetFiles(filespec As String, Optional Attributes As VbFileAttribute) As String() Dim result() As String Dim filename As String, count As Long, path2 As String Const ALLOC_CHUNK = 50 ReDim result(0 To ALLOC_CHUNK) As String filename = Dir$(filespec, Attributes) Do While Len(filename) count = count + 1 If count > UBound(result) Then ' Resize the result array if necessary. ReDim Preserve result(0 To count + ALLOC_CHUNK) As String End If result(count) = filename ' Get ready for the next iteration. filename = Dir$ Loop ' Trim the result array. ReDim Preserve result(0 To count) As String GetFiles = result End Function Function GetDirectories(path As String, Optional Attributes As VbFileAttribute, _ Optional IncludePath As Boolean) As String() Dim result() As String Dim dirname As String, count As Long, path2 As String Const ALLOC_CHUNK = 50 ReDim result(ALLOC_CHUNK) As String ' Build the path name + backslash. path2 = path If Right$(path2, 1) <> "\" Then path2 = path2 & "\" dirname = Dir$(path2 & "*.*", vbDirectory Or Attributes) Do While Len(dirname) If dirname = "." Or dirname = ".." Then ' Exclude the "." and ".." entries. ElseIf (GetAttr(path2 & dirname) And vbDirectory) = 0 Then ' This is a regular file. Else ' This is a directory. count = count + 1 If count > UBound(result) Then ' Resize the result array if necessary. ReDim Preserve result(count + ALLOC_CHUNK) As String End If ' Include the path if requested. If IncludePath Then dirname = path2 & dirname result(count) = dirname End If dirname = Dir$ Loop ' Trim the result array. ReDim Preserve result(count) As String GetDirectories = result End Function

If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.