Extract filename from path

后端 未结 8 661
梦谈多话
梦谈多话 2021-01-04 08:21

I need to extract the filename from a path (a string):

e.g., \"C:\\folder\\folder\\folder\\file.txt\" = \"file\" (or even \"file.txt\" to get me sta

8条回答
  •  醉梦人生
    2021-01-04 08:27

    Here's simpler method: a one-line function to extract only the name — without the file extension — as you specified in your example:

    Function getName(pf):getName=Split(Mid(pf,InStrRev(pf,"\")+1),".")(0):End Function
    

    ...so, using your example, this:

           MsgBox getName("C:\folder\folder\folder\file.txt")

      returns:

           

    For cases where you want to extract the filename while retaining the file extension, or if you want to extract the only the path, here are two more single-line functions:

    Extract Filename from x:\path\filename:

    Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function
    

    Extract Path from x:\path\filename:

    Function getPath(pf)As String: getPath=Left(pf,InStrRev(pf,"\")): End Function
    

    Examples:
    examples

    (Source)

提交回复
热议问题