简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM