0

My code below is used to select a file and load the file path into the textbox. I am trying to extract just the file name from this and put that in the textbox. I am sure there is a simple way to do this, but I cannot find out how. Thank you for any help!

Private Sub openDialog1()
Dim fd As Office.FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd

  .AllowMultiSelect = False

  .Title = "Please select the report."

  .Filters.Clear
  .Filters.Add "Excel 2003", "*.xls"
  .Filters.Add "All Files", "*.*"

  If .Show = True Then
    TextBox1 = .SelectedItems(1)

  End If
End With
End Sub
Community
  • 1
  • 1
Tyler
  • 45
  • 1
  • 6
  • 14
  • possible duplicate of [How to extract file name from path?](http://stackoverflow.com/questions/1743328/how-to-extract-file-name-from-path) – Gareth Feb 17 '15 at 15:29
  • Somehow did not find this in my searching, I'll see if I can work it out from this. – Tyler Feb 17 '15 at 15:39
  • Cool, give it a try (I'd suggest using the `FileSystemObject` method in the second answer). – Gareth Feb 17 '15 at 15:42
  • I got it to work with the FileSystemObjectMethod, but do I need to select the Tools> references >Microsoft Scripting Runtime feature on every computer I run this code on? If that is so then I cannot use it. – Tyler Feb 17 '15 at 15:52
  • No, you only need to load Microsoft Scripting Runtime feature to the workbook with the code. – Mitch Feb 17 '15 at 17:51

1 Answers1

2

You just need to discard the path part. This will display the filename.ext

Sub openDialog1()
Dim fd As Office.FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd

  .AllowMultiSelect = False

  .Title = "Please select the report."

  .Filters.Clear
  .Filters.Add "Excel 2003", "*.xls"
  .Filters.Add "All Files", "*.*"

  If .Show = True Then
    ary = Split(.SelectedItems(1), "\")
    MsgBox ary(UBound(ary))
  End If
End With
End Sub
Gary's Student
  • 95,722
  • 10
  • 59
  • 99
  • Your solution was effective and much less complicated than the 'FileSystemObject' method. Thank you. – Tyler Feb 17 '15 at 18:47