Share via

Finding the Folder Path for a file

Anonymous
2020-05-17T18:27:18+00:00

I am trying to build a function that would return the folder path given the filepath.

I.e.,

 Function folderPath (filePath as string) as string

End function

If filePath is:

               "C:\Users\Owner\Downloads\SMR_HW_Delivery on Site.xlsm"

I want the function to return:

               "C:\Users\Owner\Downloads\

This is what I have so far, haven't tested it yet to see if it would work or not. Any suggestions, or revisions, would be greatly appreciated:

Function filePath(pathString, turnType As String) As String

'

' Returns the filename, or the folder path, from a

' folderpath\filename string

'====================================================================

Dim temp As Variant

Dim fileNameonly As String

Dim folderPathonly As String

Dim Length As Integer

'--------------------------------------------------------------------

    Length = Len(pathString)

    temp = Split(pathString, Application.PathSeparator)

    fileNameonly = temp(uBound(temp))

    folderPathonly = Mid(pathString, 1, Length - Len(fileNameonly))

    If turnType = "File" Then

        filePath = fileNameonly

    ElseIf turnType = "Folder" Then

        filePath = folderPathonly

    End If

End Function

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

HansV 462.6K Reputation points
2020-05-17T19:13:51+00:00

Here is a slightly shorter version:

Function filePath(pathString, turnType As String) As String

    ' Returns the filename or the folder path

    ' from a folderpath\filename string

    Dim p As Long

    p = InStrRev(pathString, "")

    If turnType = "File" Then

        filePath = Mid(pathString, p + 1)

    ElseIf turnType = "Folder" Then

        filePath = Left(pathString, p)

    End If

End Function

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2020-05-17T19:27:09+00:00

    That's perfect. Waste not want not. Compact. I love it.

    Was this answer helpful?

    0 comments No comments