I have the following code that does two tasks: First, if the last parameter is True (to list all the files in folders and subfolders) and this is done well
Second, if the last parameter is False (to list all the folders and subfolders in a main folder)
Here's my try till now
Code: Select all
Sub Test_ListFolders()
Dim fso As Object, sPath As String
Set fso = CreateObject("Scripting.FileSystemObject")
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then sPath = fso.GetFolder(.SelectedItems(1)).Path Else Exit Sub
End With
With shHelper.Columns("G:H")
.ClearContents: .NumberFormat = "@"
End With
ListFilesInFolder sPath, True, False
End Sub
Sub ListFilesInFolder(sourceFolderName As String, includeSubfolders As Boolean, ByVal bFiles As Boolean)
Dim fileItem As Object, subFolder As Object, r As Long
With shHelper
r = .Range(IIf(bFiles, "A", "G") & .Rows.Count).End(xlUp).Row + 1
r = IIf(IIf(bFiles, .Range("A1").Value, .Range("G1").Value) = Empty, 1, r)
End With
With CreateObject("Scripting.FileSystemObject")
With .GetFolder(sourceFolderName)
If bFiles Then
For Each fileItem In .Files
shHelper.Cells(r, 1) = Split(fileItem.Name, ".")(0)
shHelper.Cells(r, 2) = fileItem.Path
r = r + 1
Next fileItem
End If
If includeSubfolders Then
For Each subFolder In .SubFolders
ListFilesInFolder subFolder.Path, True, bFiles
If bFiles = False Then
shHelper.Cells(r, 7) = subFolder.Name
shHelper.Cells(r, 8) = subFolder.Path
r = r + 1
End If
Next subFolder
End If
End With
End With
End Sub