VBA to list files and subfolder

Dampa88

Board Regular
Joined
Apr 28, 2016
Messages
53
Office Version
  1. 365
Platform
  1. Windows
Dears,

I'm trying to update a code found on the web to list all files and subfolder in a folder.
The problem I'm having is that I do not want to list also the content of subfolders.

Example:
Folder C:\Test

Content
C:\Test\Test1.txt
C:\Test\Sub\Test2.txt

Output
C:\Test\Test1.txt or Test1.txt
C:\Test\Sub or Sub

Below the code I'm trying to update

VBA Code:
Sub ListAllFilesInAFolder()
 
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")
 
Set oFolder = oFSO.GetFolder("C:\Test")

For Each oFile In oFolder.Files
 
    Cells(i + 1, 1) = oFile.Name
 
    i = i + 1
 
Next oFile
 
End Sub

Thank you,
D
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
How about
VBA Code:
Sub ListAllFilesInAFolder()
 
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")
 
Set oFolder = oFSO.GetFolder("C:\Test")

For Each oFile In oFolder.Files
    Cells(i + 1, 1) = oFile.Name
    i = i + 1
Next oFile
For Each oFile In oFolder.subfolders
   Cells(i + 1, 1) = oFile.Name
   i = i + 1
Next
End Sub
 
Upvote 0
You're welcome & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,224,824
Messages
6,181,187
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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