Sub FindFiles()
Dim ws As Worksheet, fso As Object, fld As Object, rootfld As String, iStartRow As Long, iStartColumn As Long
Dim sNameMatch As String, bAddHyperlink As Boolean, bFullPath As Boolean
Application.ScreenUpdating = False
iStartRow = 2 ' Start list at row 2
iStartColumn = 1 ' List files and folders in column 'A'
Set ws = Worksheets("Sheet1")
'Set ws = ActiveSheet
sNameMatch = "ALL" ' List ALL files
'sNameMatch = "LookForFilesWithThisStringInTheName" ' List only the files with this string in the name
bAddHyperlink = False ' Add a hyperlink?
bFullPath = False ' Show the full path?
rootfld = "C:\Documents and Settings\user1\My Documents\Test\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(rootfld)
Call ListFiles(ProcessFolder:=fld, ListSheet:=ws, ListRow:=iStartRow, ListColumn:=iStartColumn, FileNameMatch:=sNameMatch, _
AddHyperLink:=bAddHyperlink, ShowFullPath:=bFullPath)
'ws.Cells(1, 1).Select
Set fso = Nothing
Set fld = Nothing
Application.ScreenUpdating = True
End Sub
Private Sub ListFiles(ProcessFolder As Object, ByRef ListSheet As Worksheet, ListRow As Long, ListColumn As Long, _
FileNameMatch As String, AddHyperLink As Boolean, ShowFullPath As Boolean)
Dim fil As Object, subfld As Object
For Each fil In ProcessFolder.Files
If InStr(fil.Name, FileNameMatch) <> 0 Or LCase(FileNameMatch) = "all" Then
With ListSheet
If ShowFullPath Then
If AddHyperLink Then
.Hyperlinks.Add .Cells(ListRow, ListColumn), fil.path
Else
.Cells(ListRow, ListColumn).Value = fil.path
End If
Else
If AddHyperLink Then
.Hyperlinks.Add .Cells(ListRow, ListColumn), fil.path, , , fil.Name
Else
.Cells(ListRow, ListColumn).Value = fil.Name
End If
End If
End With
ListRow = ListRow + 1
End If
Next fil
For Each subfld In ProcessFolder.SubFolders
With ListSheet
If ShowFullPath Then
If AddHyperLink Then
.Hyperlinks.Add .Cells(ListRow, ListColumn), subfld.path
Else
.Cells(ListRow, ListColumn).Value = subfld.path
End If
Else
If AddHyperLink Then
.Hyperlinks.Add .Cells(ListRow, ListColumn), subfld.path, , , subfld.Name
Else
.Cells(ListRow, ListColumn).Value = subfld.Name
End If
End If
ListRow = ListRow + 1
End With
Call ListFiles(ProcessFolder:=subfld, ListSheet:=ListSheet, ListRow:=ListRow, ListColumn:=ListColumn, _
FileNameMatch:=FileNameMatch, AddHyperLink:=AddHyperLink, ShowFullPath:=ShowFullPath)
Next subfld
Set fil = Nothing
Set subfld = Nothing
End Sub
However there are two problems with the above coding: