Get list of sub-directories
Posted by JAF on September 18, 2000 4:43 AM
Hi
I have some code (which I got from somewhare else - I dodn't write it!) which generates a list of files within a user specified directory (code at end of message).
This comes in very useful, but what I need now is something to generate a list of sub-directories (not file names) within a user specified directory.
I've tried mucking about with the above code, but it's beyond my level of VBA knowledge.
Any suggestions?
JAF
Code for generating list of files in a directory...
'32-bit API declarations
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Sub ListFiles()
Workbooks.Add
Msg = "Select a location containing the files you want to list."
Directory = GetDirectory(Msg)
If Directory = "" Then Exit Sub
If Right(Directory, 1) <> "\" Then Directory = Directory & "\"
r = 1
' Insert headers
Cells.ClearContents
Cells(r, 1) = "FileName"
Cells(r, 2) = "Size"
Cells(r, 3) = "Date/Time"
Range("A1:C1").Font.Bold = True
r = r + 1
Columns("A:C").EntireColumn.AutoFit
Range("B1:C1").HorizontalAlignment = xlRight
' Get first file
On Error GoTo error_trap
f = Dir(Directory, 7)
Cells(r, 1) = f
Cells(r, 2) = FileLen(Directory & f)
Cells(r, 3) = FileDateTime(Directory & f)
' Get remaining files
Do While f <> ""
f = Dir
If f <> "" Then
r = r + 1
Cells(r, 1) = f
Cells(r, 2) = FileLen(Directory & f)
Cells(r, 3) = FileDateTime(Directory & f)
End If
Loop
Columns("A:C").EntireColumn.AutoFit
Range("B1:C1").HorizontalAlignment = xlRight
Exit Sub
error_trap:
MsgBox "No files in specified directory."
Exit Sub
End Sub
Function GetDirectory(Optional Msg) As String
Dim bInfo As BROWSEINFO
Dim path As String
Dim r As Long, x As Long, pos As Integer
' Root folder = Desktop
bInfo.pidlRoot = 0&
' Title in the dialog
If IsMissing(Msg) Then
bInfo.lpszTitle = "Select a folder."
Else
bInfo.lpszTitle = Msg
End If
' Type of directory to return
bInfo.ulFlags = &H1
' Display the dialog
x = SHBrowseForFolder(bInfo)
' Parse the result
path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetDirectory = Left(path, pos - 1)
Else
GetDirectory = ""
End If
End Function