如果我有文件的完整路径:
eg. c:\files\file.txt
获取此文件的文件夹的最简单方法是什么:eg. c:\files\
?
答案 0 :(得分:7)
使用FileSystemObject.GetParentFolderName(strFullFilePath)
,例如
Dim strFullFilePath As String
strFullFilePath = "c:\files\file.txt"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
MsgBox fso.GetParentFolderName(strFullFilePath)
请注意,这会返回c:\file
而不是c:\file\
答案 1 :(得分:6)
您可以使用InStrRev
来搜索\
,使用Left$
来提取路径位:
filename = "c:\files\file.txt"
posn = InStrRev(filename, "\")
If posn > 0 Then
pathstr = Left$(filename, posn)
Else
pathstr = ""
End If
为了便于使用,我会使用它来创建一个函数:
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
答案 2 :(得分:1)
' GetFilenameWithoutExtension: Return filename without extension from complete path
Public Function GetFilenameWithoutExtension(path As String) As String
Dim pos As Integer
Dim filename As String
pos = InStrRev(path, "\")
If pos > 0 Then
filename = Mid$(path, pos + 1, Len(path))
GetFilenameWithoutExtension = Left(filename, Len(filename) - Len(Mid$(filename, InStrRev(filename, "."), Len(filename))))
Else
GetFilenameWithoutExtension = ""
End If
End Function
' GetFilenameWithExtension: Return filename with extension from complete path
Public Function GetFilenameWithExtension(path As String) As String
Dim pos As Integer
pos = InStrRev(path, "\")
If pos > 0 Then
GetFilenameWithExtension = Mid$(path, pos + 1, Len(path))
Else
GetFilenameWithExtension = ""
End If
End Function
' GetDirectoryFromPathFilename: Return directory path contain filename
Public Function GetDirectoryFromPathFilename(path As String) As String
Dim pos As Integer
pos = InStrRev(path, "\")
If pos > 0 Then
GetDirectoryFromPathFilename = Left$(path, pos)
Else
GetDirectoryFromPathFilename = ""
End If
End Function