I need the path name and file name of the file that is opened with File Dialog. I want to show this information with a hyperlink in my worksheet.
With this code I have the file path:
Sub GetFilePath()
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
ActiveSheet.Range("A1") = FileSelected
End Sub
I'm still looking for a way to get the filename.
Excel VBA FileDialog – Example #1Step 1: Go to the Developers tab and click on Visual Basic. Step 2: Open a Module from the Insert menu option as shown below. Step 3: Start the subprocedure to start working on example. Step 4: Declare a variable as Filedialog as shown below.
To display a file dialog box by using the FileDialog object, you must use the Show method. After a dialog box is displayed, no code executes until the user dismisses the dialog box. The following example creates and displays a File Picker dialog box, and then displays each selected file in a message box.
The Open dialog box lets the user specify the drive, directory, and the name of a file or set of files to open. You create and display an Open dialog box by initializing an OPENFILENAME structure and passing the structure to the GetOpenFileName function.
FileNameOnly = Dir(.SelectedItems(1))
You can get any part of the file path using the FileSystemObject. GetFileName(filepath) gives you what you want.
Modified code below:
Sub GetFilePath()
Dim objFSO as New FileSystemObject
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
ActiveSheet.Range("A1") = FileSelected 'The file path
ActiveSheet.Range("A2") = objFSO.GetFileName(FileSelected) 'The file name
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With