【问题标题】:Excel Vba - Pull File Name from File PathExcel Vba - 从文件路径中提取文件名
【发布时间】:2015-02-17 15:28:34
【问题描述】:

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

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

【问题讨论】:

  • 不知何故在我的搜索中没有找到这个,我看看能不能解决这个问题。
  • 酷,试一试(我建议在第二个答案中使用FileSystemObject 方法)。
  • 我让它与 FileSystemObjectMethod 一起工作,但我是否需要在我运行此代码的每台计算机上选择工具> 参考>Microsoft 脚本运行时功能?如果是这样,那么我不能使用它。
  • 不,您只需要使用代码将 Microsoft Scripting Runtime 功能加载到工作簿中即可。

标签: excel filenames vba


【解决方案1】:

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

【讨论】:

  • 您的解决方案比“FileSystemObject”方法有效且简单得多。谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 2016-06-19
  • 2010-10-01
  • 2010-12-26
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
相关资源
最近更新 更多