如果我有一个文件的完整路径:
eg. c:\files\file.txt
Run Code Online (Sandbox Code Playgroud)
获取此文件的文件夹的最简单方法是 eg. c:\files\
什么?
您可以InStrRev
用于搜索\
和Left$
提取路径位:
filename = "c:\files\file.txt"
posn = InStrRev(filename, "\")
If posn > 0 Then
pathstr = Left$(filename, posn)
Else
pathstr = ""
End If
Run Code Online (Sandbox Code Playgroud)
为了便于使用,我会使用它来创建一个函数:
Function pathOfFile(fileName As String) As String
Dim posn As Integer
posn = InStrRev(fileName, "\")
If posn > 0 Then
pathOfFile = Left$(filename, posn)
Else
pathOfFile = ""
End If
End Function
Run Code Online (Sandbox Code Playgroud)
使用FileSystemObject.GetParentFolderName(strFullFilePath)
例如
Dim strFullFilePath As String
strFullFilePath = "c:\files\file.txt"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
MsgBox fso.GetParentFolderName(strFullFilePath)
Run Code Online (Sandbox Code Playgroud)
注意这会返回c:\file
而不是c:\file\