VBA Drive Directory

christian2016

Board Regular
Joined
Oct 6, 2016
Messages
123
Hi Guys,

Need a code which list the full file path of all folders, sub folders and files held on a shared drive and writes the results within excel. So basically everything stored on the drive.

example:
Column A
C:\new folder\test.doc
C:\new folder\test2.xls
etc.

There are a lot of files on the drive so looking at something that will do it fairly quick. Less than 5 minutes.

I know I can do this in CMD but i need a vba to do it and unsure where to start.

Any help is greatly appreciated.

thanks
 
Last edited:

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
You can run a DOS DIR command from VBA and capture the output. Change the folder path to suit:

Code:
Public Sub DOS_Dir3()

    Dim folder As String
    Dim dirLines As Variant
    Dim results() As String
    Dim i As Long
        
    folder = "Z:\"
    
    dirLines = Split(CreateObject("wscript.shell").exec("cmd /c DIR /B /S /A-D """ & folder).StdOut.ReadAll, vbCrLf)    
    
    ReDim results(UBound(dirLines), 0)
    For i = 0 To UBound(dirLines)
        results(i, 0) = dirLines(i)
    Next
    
    With ActiveSheet
        .Cells.Clear
        .Range("A1").Resize(UBound(dirLines) + 1, 1).Value = results
    End With
    
End Sub
 
Upvote 0
Thanks John, works well and fast.

just a question when I run from CMD T:\>dir /b /s >testlist.txt i get a lot more results.

Is there something we can change in the code or is there a reason as to why this is happening. Also does it get filenames longer than 250 characters.

Thanks for your help
 
Upvote 0
The /A-D omits directories so that could be the reason. I don't know about the 250 character file names.
 
Upvote 0

Forum statistics

Threads
1,215,039
Messages
6,122,799
Members
449,095
Latest member
m_smith_solihull

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