View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Norman Jones Norman Jones is offline
external usenet poster
 
Posts: 5,302
Default Recursive directory listing

Hi Jim,

The following was posted by Roger Hammond to this NG earlier this year::

<<<----------------------------------------------------- START

this will spit out the contents of a folder and sub folders for either a
given file type or all types to a new sheet.

Option Explicit

Sub FullDir()
ActiveWorkbook.Sheets.Add
GetFiles "c:\my documents\my excel files\xspandxl\", ".xls"
End Sub

Sub GetFiles(strRootDir As String, Optional strType As String)
Dim strDirName As String
Dim bTypeMatch As Boolean
Dim colDirs As Collection
Dim lDirCounter As Long
Dim lIndex As Long

Set colDirs = New Collection
colDirs.Add strRootDir
lDirCounter = 1
lIndex = 1

'check for sub directories and make a recursive call to the lowest level
dirs first

Do While lDirCounter <= colDirs.Count
strRootDir = colDirs(lDirCounter)
strDirName = Dir(strRootDir, vbDirectory + vbNormal)
Do While strDirName < ""
If strDirName < "." And strDirName < ".." Then
If (GetAttr(strRootDir & strDirName) And vbDirectory) =
vbDirectory Then
'add to the directories collection so that this will be done
later
colDirs.Add strRootDir & strDirName & "\"
Else
'we found a normal file
bTypeMatch = False
If strType = "*.*" Then
bTypeMatch = True
ElseIf UCase(Right(strDirName, Len(strType))) =
UCase(strType) Then
bTypeMatch = True
End If
If bTypeMatch = True Then
'we found a valid file
Cells(lIndex, 1) = strRootDir & strDirName
lIndex = lIndex + 1
End If
End If
End If
strDirName = Dir
Loop
lDirCounter = lDirCounter + 1
Loop
End Sub

Robin Hammond
www.enhanceddatasystems.com

<<<----------------------------------------------------- END

---
Regards,
Norman



"Jim" wrote in message
...
Is it possible to perform a recursive directory listing using VBA ? I can
manage to go down one level but am struggling to code for (more than one)
recursion, i.e. all files in all sub directories of a directory.

Regards, Jim.