0

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

A nice solution to split the path into an array. Personally I prefer several code lines with meaningful variables instead of one long code line with several methods in it.
You'll find that the Split method can be very useful in returning portions of delimited strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.