Hey Guys,
In need of some assistance. Basically, my objective is to get the list of files inside a particular directory. Directory includes many subfolders and inside those we again have 'n' number of folders. Am able to successfully get the file list if they in the parent or within 1-level subfolders. I need to get the list of files from 'n' number of levels of directory.
Sub ListFilesFromFolderAndSubFolders()
'
' http://vbaexpress.com/forum/showthread.php?t=10829&page=2
'
Dim f As Object, fso As Object, flder As Object
Dim extn As String, IsXLFile As Boolean
Dim folder As String
Dim wb As Workbook, ws As Worksheet
Dim TotalFiles As Long, TotalFolders As Long
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Set fso = CreateObject("Scripting.FileSystemObject")
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then
End
End If
folder = .SelectedItems(1) 'vPath
End With
For Each f In fso.GetFolder(folder).Files
extn = Right(f.Name, Len(f.Name) - InStrRev(f.Name, "."))
Select Case extn
Case "xlsx": IsXLFile = True
Case "xlsb": IsXLFile = True
Case "xlsm": IsXLFile = True
Case "xls": IsXLFile = True
Case Else: IsXLFile = False
End Select
If IsXLFile = True And CDate(f.DateLastModified) >= CDate("8/11/2013 0:00:00") Then
ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0) = f.Path
End If
Next
For Each flder In fso.GetFolder(folder).SubFolders
For Each f In fso.GetFolder(flder.Path).Files
extn = Right(f.Name, Len(f.Name) - InStrRev(f.Name, "."))
Select Case extn
Case "xlsx": IsXLFile = True
Case "xlsb": IsXLFile = True
Case "xlsm": IsXLFile = True
Case "xls": IsXLFile = True
Case Else: IsXLFile = False
End Select
'ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0) = f.Name
'ws.Range("C" & ws.Rows.Count).End(xlUp).Offset(1, 0) = Right(f.Name, Len(f.Name) - InStrRev(f.Name, "."))
'ws.Range("C" & ws.Rows.Count).End(xlUp).Offset(1, 0) = CDate(f.DateLastModified)
If IsXLFile = True And CDate(f.DateLastModified) >= CDate("8/11/2013 0:00:00") Then
ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0) = f.Path
End If
Next
Next
End Sub
Thing is, I don't have pre-defined knowledge of how many levels it could be as it is defined by the users. With my above code, I know I'll have to repeat the loop for SubFolders and Files in them to the times the levels available. So I just need to know how many times, I'll have to loop or so..
Am very much fond of new thoughts and suggestions if something better hit your heads.. Open for thoughts!
Bookmarks