Selected Answer
Hi again Kalil
In the attached revised file, you'll see:
- column B is headed "File name (without extension)"
- column C is headed "Full path and full filename" - this it to show where the file in column B is located within the directory structure
- a blue button in column A, ;labelled "List files in all subfolders".
Clicking that button will run the revised code below, where:
- changes and comments are in bold
- some of your code is moved to a Function (see below)
- to search subfolders, I use the FileSystemObject object (in the variable objFSO)
- your variable i is declared before this routine (so it's value isn't lost when the Function is called).
Dim i As Long
Sub MorshedDhaka()
Dim Fldr As String, Fname As String
Dim objFldr As Object
Dim objSubFldr As Object
i = 1
Set objFldr = Application.FileDialog(4)
With objFldr
.Title = "Choose a folder"
.AllowMultiSelect = False
If .Show = -1 Then Fldr = .SelectedItems(1)
End With
If Fldr = "" Then Exit Sub
' enable use of FSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
' clear any previous results (shrinking file size)
ActiveSheet.UsedRange.Offset(1, 0).EntireRow.Delete
Set objFldr = objFSO.GetFolder(Fldr)
' call function
LoopEachFolder objFldr
' quit FSO
Set objFSO = Nothing
' fit results and tell user
Columns("B:C").AutoFit
MsgBox "Done! Listed " & i - 1 & " files"
End Sub
After the user picks a folder, the code clears any existing results then this line:
LoopEachFolder objFldr
calls the new Function below (in the same Module) and passes the folder to it:
Function LoopEachFolder(fldFolder As Object)
Dim objFldLoop As Object
Fname = Dir(fldFolder & "\")
' List files in this folder
Do While Fname <> ""
i = i + 1
'write full path in column C
Cells(i, 3) = fldFolder.Path & "\" & Fname
'write filename (without extension) in column B
Cells(i, 2) = Split(Fname, ".")(0)
' get next file (if any)
Fname = Dir()
Loop
' With the subfolders in this folder....
For Each objFldLoop In fldFolder.subFolders
' run this function on each subfolder found
LoopEachFolder objFldLoop
Next objFldLoop
End Function
The crucial bit is the loop near the end- this finds any sub-folders and calls on the function itself again (and iteratively until all levels of folders have been searched).
The last lines of your revised code tidy up the results and tell the user how many files it found.
Now you'll get the file names in column B (asd before) and C will tell you exactly where those files are.
Hope this works well for you (and you remember to mark this Answer as Selected if it does!)