Vba – How to get the name of the parent folder from a file path

directorypathvba

Using VBA, is it possible to get the name of the folder that contains a file?

Input: C:\Windows\System32\notepad.exe

Output: System32

Best Answer

This will return the parent folder name:

Public Function GetParentFolderName(ByVal path As String) As String
    Dim result As String
    With fso = CreateObject("Scripting.FileSystemObject")
        result = .GetParentFolderName(path)
        GetParentFolderName = Mid(result, InStrRev(result, "\") + 1)
    End With
End Function

Usage:

Sub GetParentFolderNameTest()
    Debug.Print GetParentFolderName("C:\Windows\System32\notepad.exe")
End Sub

Output:

System32