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 ha
The code starts file search from root colon, If I want to start search from a specific directory, to avoid going to that directory every time, where I should put one. I did it like
Sub GetFilePath()
FileSelected = "G:\Audits\A2010"
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("C14") = FileSelected
End Sub
But it could not start reach from "G:\Audits\A2010"
After searching different websites looking for a solution as to how to separate the full path from the file name once the full one-piece information has been obtained from the Open File Dialog, and seeing how "complex" the solutions given were for an Excel newcomer like me, I wondered if there could be a simpler solution. So I started to work on it on my own and I came to this possibility. (I have no idea if somebody got the same idea before. Being so simple, if somebody has, I excuse myself.)
Dim fPath As String Dim fName As String Dim fdString As String fdString = (the OpenFileDialog.FileName) 'Get just the path by finding the last "\" in the string from the end of it fPath = Left(fdString, InStrRev(fdString, "\")) 'Get just the file name by finding the last "\" in the string from the end of it fName = Mid(fdString, InStrRev(fdString, "\") + 1) 'Just to check the result Msgbox "File path: " & vbLF & fPath & vbLF & vblF & "File name: " & vbLF & fName
AND THAT'S IT!!! Just give it a try, and let me know how it goes...
FileNameOnly = Dir(.SelectedItems(1))
The below command is enough to get the path of the file from a dialog box -
my_FileName = Application.GetOpenFilename("Excel Files (*.tsv), *.txt")
To extract only the filename from the path, you can do the following:
varFileName = Mid(fDialog.SelectedItems(1), InStrRev(fDialog.SelectedItems(1), "\") + 1, Len(fDialog.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