Home » excel » VBA – Import list of folders into excel range

VBA – Import list of folders into excel range

Posted by: admin May 14, 2020 Leave a comment


I am currently working on a macro that imports files from a number of subfolders within a folder named “simulations” which is in the current working directory. The code I have is working for everything I need except the last step which is importing the file list into excel.

Currently, I have a macro which reads a file I create by hand using the cmd line:

> dir /b > foldernames.txt

I then open this file in another excel window and then copy the range into my current excel workbook. This seems like a slow, roundabout way of doing this and am looking for macro solutions that can circumvent this.

I have tried a number of code combinations using things like:

Dim Fold As Folder
Dim FS As FileSystemObject

I suspect that most of the syntax I’ve tried is not compatible with 2007 onwards. Are there certain functions that would be helpful for this application? I don’t need code written for, just suggestions about applicable functions so I can play with those.

How to&Answers:

We run the CMD command via Shell

Sub RunDir()
    x = Shell("cmd.exe /c dir /b > C:\TestFolder\foldernames.txt", 1)
    Close #1
    Open "C:\TestFolder\foldernames.txt" For Input As #1
    j = 1
     Do While Not EOF(1)
            Line Input #1, TextLine
            Cells(j, 1) = TextLine
            j = j + 1
    Close #1
End Sub

I use TestFolder as the destination for the Dir…………..pick your own