Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected path and name of the file opened with file dialog?

Tags:

excel

vba

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.

like image 314
VeVi Avatar asked Oct 02 '12 09:10

VeVi


People also ask

How do I use FileDialog in Excel VBA?

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.

Which method would you use to display a dialog box that lets a user select the file to be opened?

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.

Which function is used for opening the file dialog 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.


2 Answers

FileNameOnly = Dir(.SelectedItems(1))

like image 84
Ace1000 Avatar answered Oct 28 '22 04:10

Ace1000


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
like image 40
meticoeus Avatar answered Oct 28 '22 04:10

meticoeus