我只想从一个完全合格的名称来选择路径。
例如, C:\Newfolder\iTDC.mdb
示于在文本框中。
但我想只拿C:\Newfolder
,去除iTDC.mdb
。
如何跳过文件?
我只想从一个完全合格的名称来选择路径。
例如, C:\Newfolder\iTDC.mdb
示于在文本框中。
但我想只拿C:\Newfolder
,去除iTDC.mdb
。
如何跳过文件?
快速和肮脏
Dim sPath As String
sPath = "C:\Newfolder\iTDC.mdb"
sPath = Left(sPath, InStrRev(sPath, "\"))
如果您添加到Microsoft脚本运行时参考(使用项目- >引用),那么你可以使用FileSystemObject
做文件相关的操作。 例如:
Dim oFSO as New FileSystemObject
strFolder = oFSO.GetFolder(strPath)
该FileSystemObject
还具有用于构成路径(其他有用的方法BuildPath
)和用于测试文件,文件夹等。(存在FileExists
, FolderExists
)。
您可以使用PathRemoveFileSpec从2000年的功能,在Windows的每个版本和98这里是一个VB6实现。
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
我倾向于避免Microsoft脚本运行(包括FileSystemObject的)。 在我的经验,它偶尔打破用户的机器,也许是因为他们的IT部门是偏执病毒。 还有其他有用的功能在SHLWAPI.DLL,例如用于测试是否存在的文件夹或文件存在 。
' 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