Browse Folder to Select Excel File

Code Block with Copy Button
    
Sub BrowseForFilePath()

Dim fDialog As FileDialog
Dim filePath As String

' Create a FileDialog object as a File Picker dialog
Set fDialog = Application.FileDialog
(msoFileDialogFilePicker)

With fDialog
' Set the title of the dialog box
   .Title = "Select a File"

' Clear any existing filters
  .Filters.Clear

 ' Add a filter for Excel files
 .Filters.Add "Excel Files", "*.xlsx;*.xls;*.xlsm"

 ' Add a filter for All Files
  .Filters.Add "All Files", "*.*"

  ' Set the initial folder (optional)
 ' .InitialFileName = "C:\MyDocuments\"
    
 ' Allow only single selection
  .AllowMultiSelect = False
    
 ' Show the dialog box and check if a file was selected
   If .Show = True Then
    
   ' Get the selected file path
    filePath = .SelectedItems(1)
    
  ' Display the file path (e.g., in a message box or a cell)
  MsgBox "Selected file path: " & filePath
    
 ' Alternatively, place it in a cell:
 ' Range("A1").Value = filePath
 Else
     MsgBox "No file was selected."
 End If

End With

' Release the object
Set fDialog = Nothing

End Sub

Post a Comment

Previous Post Next Post