Sharunas Bielskis
Sharunas Bielskis

Reputation: 1213

Get folder name from path in Excel VBA

I didn't find through searching in internet simple solution for this purpose which can be quickly integrated into my code. I propose my solution.

Upvotes: 0

Views: 2301

Answers (2)

Ron Rosenfeld
Ron Rosenfeld

Reputation: 60414

You can actually do this with a single line of code:

Function GetFolderNameFromPath(folderPath As String) As String
    GetFolderNameFromPath = Split(folderPath, Application.PathSeparator)(UBound(Split(folderPath, Application.PathSeparator)))
End Function

Upvotes: 2

Sharunas Bielskis
Sharunas Bielskis

Reputation: 1213

As this function from time to time, I need in my projects I decided to create a separate function for it. The code of it is below:

Function GetFolderNameFromPath(folderPath As String) As String

Dim lastPathSeparatorPosition As Long, folderPathLength As Long, folderNameLength As Long

lastPathSeparatorPosition = InStrRev(folderPath, Application.PathSeparator)
folderPathLength = Len(folderPath)
folderNameLength = folderPathLength - lastPathSeparatorPosition
GetFolderNameFromPath = Right(folderPath, folderNameLength)

End Function

Upvotes: 2

Related Questions