Browse folder and list all the file names in sheet

jayymehta

New Member
Joined
Jan 3, 2018
Messages
18
Hi, I made a user form consisting of a Command Button "Browse". When a user clicks on it, a dialog box appears to search for a folder. Now when a folder is selected, I want that the Name of all the Files inside that selected Folder should be copied in my excel sheet.
I tried coding for the same, here's my try:
Code:
Private Sub CommandButton1_Click()Dim fName As Object
Dim fObjct As Object
With Application.FileDialog(msoFileDialogFolderPicker)
    If .Show = -1 Then
        fName = .SelectedItems(1)
    End If
End With


If fName <> "" Then
    For Each fObjct In fName
        Sheets("Sheet5").Cells(i + 1, 5) = fObjct.Name
        i = i + 1
    Next fObjct
End If
End Sub

I tried running this code, but it shows error in the line
fName = .SelectedItems(1)
"Object Variable or With variable not set".
Can anyone help me code this?
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
Hi & welcome to the board.
How about this
Code:
Sub GetFileNames()

   Dim FldrPth As String
   Dim fName As String
   Dim Fldr As Object
   Dim Cnt As Long
   
   Set Fldr = Application.FileDialog(4)
   With Fldr
      .title = "Select a Folder"
      .AllowMultiSelect = False
      If .Show <> -1 Then Exit Sub
      FldrPth = .SelectedItems(1)
   End With
   
   FldrPth = FldrPth & "\"
   fName = Dir(FldrPth & "*")
   Do While Len(fName) > 0
      Cnt = Cnt + 1
      Sheets("Sheet1").Range("E" & Cnt).Value = fName
      fName = Dir
   Loop

End Sub
 
Upvote 0
Glad to help & thanks for the feedback.

The 4 represents msoFileDialogFolderPicker but it means you don't need to set a reference in the VBE to the Microsoft Office xx.0 Object Library
 
Upvote 0

Forum statistics

Threads
1,223,231
Messages
6,170,885
Members
452,364
Latest member
springate

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