excel - 如何只获取文件名而不是打开文件的整个文件路径?

标签 excel vba filenames getopenfilename

换句话说,调用Application.GetOpenFileName()方法后,是否需要做一些字符串处理?

最佳答案

为什么要重新发明轮子并编写大量样板代码?只需使用现有的 FileSystemObject的 GetFileName 方法,已经为您编写、测试和调试:

filename = FSO.GetFileName(path)

这是一个工作示例:

Dim path As String
Dim filename As String
Dim FSO As Scripting.FileSystemObject
Set FSO = New FileSystemObject

path = "C:\mydir\myotherdir\myfile.txt"

filename = FSO.GetFileName(path) 'Bingo. Done.

Debug.Print filename ' returns "myfile.txt"

' Other features:
Debug.Print FSO.GetBaseName(path) ' myfile
Debug.Print FSO.GetExtensionName(path) ' txt
Debug.Print FSO.GetParentFolderName(path) ' C:\mydir\myotherdir
Debug.Print FSO.GetDriveName(path) ' C:
' et cetera, et cetera.

您需要按如下方式设置引用: 工具 > 引用... > 在 Microsoft Scripting Runtime 旁边设置复选标记。

否则使用后期绑定(bind):

Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")

关于excel - 如何只获取文件名而不是打开文件的整个文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9086309/

相关文章:

excel - 数组公式结果连接到单个单元格中

php - 从文件中删除扩展名

string - VBA 多行字符串问题

python - 将文件名转换为文件 ://URL

python - 读取名称每天都在变化的 csv 文件

python - 从 VBA 运行 python 脚本

java - 无法访问 NPOIFSFileSystem

vba - Excel VBA - 更改单元格时运行宏

vba - 如何从 Excel 调用 Word 宏

vba - Powershell 使用动态参数量运行 Excel 宏