我想仅从完全限定名称中选择路径。
例如,文本框中显示了
但我只想取
如何跳过文件?
例如,文本框中显示了
C:\Newfolder\iTDC.mdb
。但我只想取
C:\Newfolder
,将 iTDC.mdb
移除。如何跳过文件?
快速而粗略
Dim sPath As String
sPath = "C:\Newfolder\iTDC.mdb"
sPath = Left(sPath, InStrRev(sPath, "\"))
如果您添加了对Microsoft Scripting Runtime的引用(使用Project->References),则可以使用FileSystemObject
进行文件相关操作。例如:
Dim oFSO as New FileSystemObject
strFolder = oFSO.GetFolder(strPath)
FileSystemObject
还有其他有用的方法,用于组合路径(BuildPath
),以及测试文件、文件夹等是否存在(FileExists
,FolderExists
)。
Private Declare Function PathRemoveFileSpec Lib "Shlwapi" _
Alias "PathRemoveFileSpecW" (ByVal szPath As Long) As Long
'Convert input file path to drive & directory only. (Supports UNC too) '
Function sPathOnly(ByVal sInput As String) As String
Dim sWorking As String
sWorking = sInput
If (PathRemoveFileSpec(StrPtr(sWorking)) <> 0) Then
'Call succeeded. Trim trailing Null '
sPathOnly = sTrimNull(sWorking)
Else
sPathOnly = sWorking
End If
End Function
'Trim trailing null characters (e.g. from a string returned from an API call) '
Function sTrimNull(ByVal sIn As String) As String
Dim iZeroCharacter As Long
iZeroCharacter = InStr(sIn, Chr$(0))
If iZeroCharacter > 0 Then
sTrimNull = Left$(sIn, iZeroCharacter - 1)
Else
sTrimNull = sIn
End If
End Function
' 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