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
5
  • possible duplicate of How to extract file name from path? Commented Feb 17, 2015 at 15:29
  • Somehow did not find this in my searching, I'll see if I can work it out from this. Commented Feb 17, 2015 at 15:39
  • Cool, give it a try (I'd suggest using the FileSystemObject method in the second answer). Commented Feb 17, 2015 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. Commented Feb 17, 2015 at 15:52
  • No, you only need to load Microsoft Scripting Runtime feature to the workbook with the code. Commented Feb 17, 2015 at 17:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution was effective and much less complicated than the 'FileSystemObject' method. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.