You could use application.filesearch:
Sub Tester2()
With Application.FileSearch
.NewSearch
.LookIn = "C:\My Documents"
.SearchSubFolders = True
.FileName = "*.xls"
' .MatchTextExactly = True
' .FileType = msoFileTypeAllFiles
.FileType = msoFileTypeExcelWorkbooks
If .Execute() 0 Then
MsgBox "There were " & .FoundFiles.Count & _
" file(s) found."
For i = 1 To .FoundFiles.Count
Workbooks.Open .FoundFiles(i)
Next i
Else
MsgBox "There were no files found."
End If
End With
End Sub
That is the easiest, but some claim they have problems with it.
Here is some that uses DIR as you are doing:
This is code that Bill Manville do some years ago. Seems to still work<g:
Option Base 1
Dim aFiles() As String, iFile As Integer
Sub ListAllFilesInDirectoryStructure()
Dim Counter As Integer
iFile = 0
ListFilesInDirectory "c:\test\" ' change the top level as you wish
For Counter = 1 To iFile
Worksheets("Sheet1").Cells(Counter, 1).Value = aFiles(Counter)
Next
End Sub
Sub ListFilesInDirectory(Directory As String)
Dim aDirs() As String, iDir As Integer, stFile As String
' use Dir function to find files and directories in Directory
' look for directories and build a separate array of them
' note that Dir returns files as well as directories when vbDirectory
specified
iDir = 0
stFile = Directory & Dir(Directory & "*.*", vbDirectory)
Do While stFile < Directory
If Right(stFile, 2) = "\." Or Right(stFile, 3) = "\.." Then
' do nothing - GetAttr doesn't like these directories
ElseIf GetAttr(stFile) = vbDirectory Then
' add to local array of directories
iDir = iDir + 1
ReDim Preserve aDirs(iDir)
aDirs(iDir) = stFile
Else
' add to global array of files
iFile = iFile + 1
ReDim Preserve aFiles(iFile)
aFiles(iFile) = stFile
End If
stFile = Directory & Dir()
Loop
' now, for any directories in aDirs call self recursively
If iDir 0 Then
For iDir = 1 To UBound(aDirs)
ListFilesInDirectory aDirs(iDir) & Application.PathSeparator
Next iDir
End If
End Sub
Other references:
http://support.microsoft.com/kb/185476/EN-US/
How To Search Directories to Find or List Files
http://support.microsoft.com/kb/185601/EN-US/
HOW TO: Recursively Search Directories by Using FileSystemObject
http://support.microsoft.com/kb/186118/EN-US/
How To Use FileSystemObject with Visual Basic
--
Regards,
Tom Ogilvy
"Sige" wrote:
Is there an easy way,
to adjust above sub so that it works also on all files in the
subfolders ...??
Best Regards Sige