"IS" <fi*******@yahoo.com> wrote in message news:<bs**********@shiva.neobee.net>...
Hi,
I am trying to list all the files in a directory and add them to a
collection. As well, I am trying to add all the files to this collection
that might be in subdirectories (if exist).
Any hints to how I do this? With Dir$ and such, I can find only single files
and directories. I guess I should be using API functions I am not aware of.
you can use Dir$, just use the optional vbDirectory flag and test
every file you get back using GetAttr. If it is a directory then save
the path in a collection or other list. When Dir$ indicates no more
check your list of directories and remove one to be processed next. a
simple example:
Dim sDir As String ' current directory
Dim sDirsLeft As String ' directories to be processed
Dim sFile As String ' current file
Dim x As Integer ' scratch
' Note: the starting directory path MUST end with a \ character
sDirsLeft = "C:\" & vbNullChar ' start with this directory
Do While Len(sDirsLeft) ' any directories left?
x = InStr(sDirsLeft, vbNullChar) ' get delimiter
sDir = Left$(sDirsLeft, x - 1) ' peel off directory
sDirsLeft = Mid$(sDirsLeft, x + 1) ' remove from to-do list
sFile = Dir$(sDir & "*.*", vbDirectory) ' get first file
Do While Len(sFile) ' any files left?
If sFile <> "." And sFile <> ".." Then ' skip self-refs
If GetAttr(sDir & sFile) And vbDirectory Then ' is it a
directory?
' yes -- add to to-do-list
sDirsLeft = sDir & sFile & "\" & vbNullChar & sDirsLeft
Else
If sFile Like "*.TXT" Then ' do we want this file?
Debug.Print sDir & sFile ' process this file
End If
End If
End If
sFile = Dir$ ' get next file
Loop
DoEvents ' just to be nice!
Loop
A better option is to use the FindFirstFile/FindNextFile/FindClose API
calls. I don't have an example handy but you can find samples at
http://groups.google.com
If you want the slowest possible method using the most overhead and a
chance of it failing on systems randomly then use the FileSystemObject