ȫ·ȡһ·ȫ· VBAVB6

һҪ

'ʹ FileSystemObjectƼ׳
' Microsoft Scripting Runtime    ѡӦ
 Sub Test()
    Dim fso As New FileSystemObject
    Dim fullPath As String
    Dim parentPath As String
    
    fullPath = "C:\Folder1\Folder2\File.txt"   ' ʾ·
    parentPath = fso.GetParentFolderName(fullPath)
    MsgBox parentPath 'أC:\Folder1\Folder2
    

    'ļβС\ûС\ؽͬ
    'ļβС\
    fullPath = "C:\Folder1\Folder2\"   ' ʾ·
    parentPath = fso.GetParentFolderName(fullPath)
    MsgBox parentPath 'أC:\Folder1
    'ļβûС\
    fullPath = "C:\Folder1\Folder2"   ' ʾ·
    parentPath = fso.GetParentFolderName(fullPath)
    MsgBox parentPath 'أC:\Folder1
End Sub

Ҫ
ַⲿãVBVBAVB.netͨ
   ͨ InStrRev  Left ȡ·
 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        MsgBoxGetParentPath("C:\Folder1\Folder2\")   'أC:\Folder1

        MsgBoxGetParentPath("C:\Folder1\Folder2")   'أC:\Folder1

        MsgBoxGetParentPath("C:\Folder1\Folder2\zyg365.txt")   'أC:\Folder1\Folder2\
 End Sub

    Function GetParentPath(ByVal fullPath As String) As String
        If Strings.Right(fullPath, 1) = "\" Then
            fullPath = Strings.Left(fullPath, Len(fullPath) - 1)  ' Ƴĩβ\
        End If
        Dim lastPos As Long
        lastPos = InStrRev(fullPath, "\")
        If lastPos > 0 Then
            GetParentPath = Strings.Left(fullPath, lastPos - 1)
        Else
            GetParentPath = ""  ' Ŀ¼޸Ŀ¼
        End If
    End Function


Ҫ
Private Declare Function PathRemoveFileSpec Lib "shlwapi" Alias "PathRemoveFileSpecA" (ByVal path As String) As Long

Function GetParentPathAPI(ByVal fullPath As String) As String
    PathRemoveFileSpec fullPath  ' ֱ޸ԭַ
    GetParentPathAPI = fullPath
End Function

Sub Test()
  '·аļ
    MsgBox GetParentPathAPI("C:\zyg365\abc\File.txt") ' أC:\zyg365\abc

  '·вļβ\û\
    MsgBox GetParentPathAPI("C:\zyg365\abc\") 'أC:\zyg365\abc
    MsgBox GetParentPathAPI("C:\zyg365\abc")  'أC:\zyg365    
End Sub
