Sub Directories

G

Guest

I need to look at all files within a directory and I need to "climb" down
sub-directories within those directories. For example:
FileDir="C:\mystuff"
I am using this loop:
FName = Dir(FileDir)
Do Until FName = ""
do stuff
Loop
But if there is a folder "c:\mystuff\subdir\" I need to look there too.
How do I determine sub-directories (folders) within folders?
 
G

Guest

Doing the digging is a bit difficult using DIR() [which is my preferred
method of digging around in folders anyway, but I recognize the
shortcomings]. Using the File System Object (FSO) works better for this.

Chip Pearson has some good examples of using the FSO with recursion (calling
itself) to work the way down through multiple levels of folders. See
http://www.cpearson.com/excel/RecursionAndFSO.htm
and even
http://www.cpearson.com/excel/CloneFolder.htm

Those should give you some good ideas and a jump start on it all.
 
G

Guest

Mike,

Add a reference to the Windows Script Host Object Model and then try
something like this:

Sub ProcessFiles()
Dim oFSO As New FileSystemObject
Dim oFolder As Folder
Dim oSubFolder As Folder
Dim oFile As File

Set oFolder = oFSO.GetFolder("C:\mystuff")

'process files in the starting folder
For Each oFile In oFolder.Files
'do stuff
Debug.Print oFile.Path
Next oFile

'process files in sub folders
For Each oSubFolder In oFolder.SubFolders
For Each oFile In oSubFolder.Files
'do stuff
Debug.Print oFile.Path
Next oFile
Next oSubFolder
End Sub
 
G

Guest

so you don't repeat your code for the file processing part, you can make the
sub a recursive one...

Sub ProcessFiles(strFolder As String)
Dim oFSO As New FileSystemObject
Dim oFolder As Folder
Dim oSubFolder As Folder
Dim oFile As File


Set oFolder = oFSO.GetFolder(strFolder)

'process files in the starting folder
For Each oFile In oFolder.Files
'do stuff
Debug.Print oFile.Path
Next oFile

'process sub folders
For Each oSubFolder In oFolder.SubFolders
ProcessFiles oSubFolder.Path
Next oSubFolder
End Sub

you then would use it like this:

Sub test()
ProcessFiles "c:\mystuff"
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top