dir function to crawl folders and list files

mAXTOR

New Member
Joined
Aug 4, 2017
Messages
1
I have code to list the content of one directory's files but need to list the files in multiple directories that are listed in row one of my spreadsheet (ex: m1, m2, m3) where m1, m2, m3 are folders. I cannot get the dir function to use a variable in my loop to pull the text of m1, m2, m3 in the cells. how do I modify the following?

Code:
Sub ListFiles()
    Dim LResult As String
    LResult = Dir("C:\Users\me\Desktop\allfileslastrun\*", vbDirectory)
    Worksheets("Report").Range("A2").Activate
    Do While Len(LResult) > 0
        ActiveCell.Formula = LResult
        ActiveCell.Offset(1, 0).Select
        LResult = Dir()
    Loop
    
End Sub
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
Welcome to MrExcel forums.

Try this:
Code:
Public Sub ListFiles()

    Dim folderCell As Range
    Dim folder As String, fileName As String, r As Long
    
    With Worksheets("Report")
        .Columns("A").ClearContents
        r = 0
        For Each folderCell In .Range("M1:M" & .Cells(Rows.Count, "M").End(xlUp).Row)
            folder = folderCell.Value
            If Right(folder, 1) <> "\" Then folder = folder & "\"
            fileName = Dir(folder & "*")
            Do While Len(fileName) > 0
                r = r + 1
                .Cells(r, 1).Value = fileName
                fileName = Dir()
            Loop
        Next
    End With
    
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,954
Messages
6,122,462
Members
449,085
Latest member
ExcelError

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top