VB code to list all files in a folder

pagrender

Well-known Member
Joined
Sep 3, 2008
Messages
652
Hello,

Is there a way to have Excel list all the names of all the files that are in one folder?

For example, in the "Budgets" folder found using Windows Explorer, there are two files named 2011-12 and 2012-13.

Is there any VB code that will list these two files in cells A1 and A2 respectively? All we are looking for is the file name in a cell.

Thanks,
Pete
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Hi. Try like this

Code:
Sub ListFiles()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
MyFolder = "C:\example"
MyFile = Dir(MyFolder & "\*.xls")
Do While MyFile <> ""
    j = j + 1
    Cells(j, 1).Value = MyFile
    MyFile = Dir
Loop
End Sub
 
Upvote 0
A very simple version would be:-
Code:
Option Explicit
 
Public Sub ListFiles()
 
  Dim sFilename As String
  Dim iRow As Integer
  
  sFilename = Dir("[COLOR=red][B]c:\temp\[/B][/COLOR]")
  iRow = 0
  Do Until sFilename = ""
    iRow = iRow + 1
    Cells(iRow, 1) = sFilename
    sFilename = Dir
  Loop
    
End Sub

You would put your folder location in place of the red bit.

Or are you wanting to navigate to the folder as part of the code?
 
Upvote 0

Forum statistics

Threads
1,224,524
Messages
6,179,304
Members
452,904
Latest member
CodeMasterX

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