Excel Vba - 从文件路径中提取文件名

时间:2015-02-17 15:28:34

标签: excel-vba filenames vba excel

下面的代码用于选择文件并将文件路径加载到文本框中。我试图从中提取文件名并将其放在文本框中。我确信有一种简单的方法可以做到这一点,但我无法找到方法。谢谢你的帮助!

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

1 个答案:

答案 0 :(得分:2)

您只需要丢弃路径部分。这将显示 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
相关问题