How to extract file name from path?











up vote
46
down vote

favorite
14












How do I extract the filename myfile.pdf from C:Documentsmyfile.pdf in VBA?










share|improve this question
























  • Try using the split function to get the file name from the path: MSDN link
    – jonaspp
    Nov 16 '09 at 16:44















up vote
46
down vote

favorite
14












How do I extract the filename myfile.pdf from C:Documentsmyfile.pdf in VBA?










share|improve this question
























  • Try using the split function to get the file name from the path: MSDN link
    – jonaspp
    Nov 16 '09 at 16:44













up vote
46
down vote

favorite
14









up vote
46
down vote

favorite
14






14





How do I extract the filename myfile.pdf from C:Documentsmyfile.pdf in VBA?










share|improve this question















How do I extract the filename myfile.pdf from C:Documentsmyfile.pdf in VBA?







string vba






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 5 '17 at 14:31









Smandoli

5,66633675




5,66633675










asked Nov 16 '09 at 16:39









Johan

8,579296287




8,579296287












  • Try using the split function to get the file name from the path: MSDN link
    – jonaspp
    Nov 16 '09 at 16:44


















  • Try using the split function to get the file name from the path: MSDN link
    – jonaspp
    Nov 16 '09 at 16:44
















Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44




Try using the split function to get the file name from the path: MSDN link
– jonaspp
Nov 16 '09 at 16:44












15 Answers
15






active

oldest

votes

















up vote
37
down vote



accepted










This is taken from snippets.dzone.com:



Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost ''
' e.g. 'c:winntwin.ini' returns 'win.ini'

If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function





share|improve this answer

















  • 1




    Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
    – Thomas Fankhauser
    Feb 24 '13 at 14:01






  • 3




    Just replace the in the code with a /.
    – Gonzalo
    Feb 25 '13 at 5:40






  • 1




    Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
    – Thomas Fankhauser
    Feb 25 '13 at 17:07






  • 3




    This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
    – Mary
    Jul 19 '13 at 18:58






  • 4




    IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
    – Matt
    Jun 28 '15 at 21:33




















up vote
109
down vote













The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).



Create a filesystem object and do all operations using that.



Dim fso as new FileSystemObject
Dim fileName As String
fileName = fso.GetFileName("c:any pathfile.txt")


The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.






share|improve this answer

















  • 13




    This answer beats the accepted answer by a mile.
    – Bob Jansen
    Dec 29 '14 at 8:28






  • 6




    In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
    – IceArdor
    Apr 27 '15 at 23:46






  • 3




    A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
    – Ian Stanway
    Nov 6 '15 at 12:21






  • 2




    @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
    – Mathieu Guindon
    Jul 13 '17 at 20:00






  • 3




    @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
    – Mathieu Guindon
    Jul 13 '17 at 20:05


















up vote
41
down vote













Dir("C:Documentsmyfile.pdf")


will return the file name, but only if it exists.






share|improve this answer



















  • 1




    +1 for "really short"
    – golimar
    Nov 13 '14 at 10:07






  • 3




    Bad because it assumes that the path is for a physical file that the program can read.
    – Skrol29
    Nov 6 '15 at 15:41










  • hi @Skrol29, could you please help to explain more on this?
    – Harry Duong
    Dec 17 '15 at 0:21










  • @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
    – Dick Kusleika
    Dec 17 '15 at 16:48










  • @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
    – Skrol29
    Dec 22 '15 at 16:08




















up vote
24
down vote













I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.



Function FileNameFromPath(strFullPath As String) As String

FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))

End Function


http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.






share|improve this answer

















  • 1




    The best for me : smart, short and does off-road.
    – Skrol29
    Nov 6 '15 at 15:51






  • 2




    +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
    – tahwos
    Oct 3 '16 at 3:45










  • I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
    – mattlore
    Sep 13 '17 at 17:53


















up vote
9
down vote













Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))





share|improve this answer























  • Not so smart because it run twice Split(sFilePath, "").
    – Skrol29
    Nov 6 '15 at 15:39


















up vote
4
down vote













If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:



Dim strFileName As String, strFolderPath As String
Dim lngIndex As Long
Dim strPath() As String

strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
strFolderPath = Join(strPath, "") 'Rebuild our path from our array


Or as a sub/function:



Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)    
Dim strPath() As String
Dim lngIndex As Long

strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
lngIndex = UBound(strPath)
o_strFileName = strPath(lngIndex) 'Get the File Name from our array
strPath(lngIndex) = "" 'Remove the File Name from our array
io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
End Sub


You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.






share|improve this answer




























    up vote
    3
    down vote













    To get the file name in an excel macro is:



    filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
    MsgBox Mid(filname, 1, InStr(filname, ".") - 1)





    share|improve this answer






























      up vote
      3
      down vote













      I can't believe how overcomplicated some of these answers are... (no offence!)



      Here's a single-line function that will get the job done:





      **Extract Filename from <code>x:pathfilename</code>:**



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




      **Extract Path from <code>x:pathfilename</code>:**



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




      Examples:



      examples






      share|improve this answer




























        up vote
        2
        down vote













        Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.



        sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)

        sFolderName = Left(sPath, Len(sPath) - Len(sFileName))


        You can test the output using this code:



        'Visual Basic for Applications 
        http = "https://www.server.com/docs/Letter.txt"
        unix = "/home/user/docs/Letter.txt"
        dos = "C:userdocsLetter.txt"
        win = "\Server01userdocsLetter.txt"
        blank = ""

        sPath = unix
        sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
        sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

        Debug.print "Folder: " & sFolderName & " File: " & sFileName


        Also see: Wikipedia - Path (computing)






        share|improve this answer




























          up vote
          2
          down vote













          The simplest approach if you are sure the file physically exists on the disk:



          Dim fileName, filePath As String
          filePath = "C:Documentsmyfile.pdf"
          fileName = Dir(filePath)


          If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:



          fileName = Mid(filePath, InStrRev(filePath, "") + 1)





          share|improve this answer




























            up vote
            1
            down vote













            Here's an alternative solution without code. This VBA works in the Excel Formula Bar:



            To extract the file name:



            =RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"","~",LEN(A1)-LEN(SUBSTITUTE(A1,"","")))))


            To extract the file path:



            =MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"",""))))+1,LEN(A1))))





            share|improve this answer






























              up vote
              0
              down vote













              I needed the path, not the filename.



              So to extract the file path in code:



              JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, ""))))) 





              share|improve this answer






























                up vote
                0
                down vote













                This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:



                'since the file name and path were used several times in code
                'variables were made public

                Public FName As Variant, Filename As String, Path As String

                Sub xxx()
                ...
                If Not GetFileName = 1 Then Exit Sub '
                ...
                End Sub

                Private Function GetFileName()
                GetFileName = 0 'used for error handling at call point in case user cancels
                FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
                If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
                Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
                Path = Left(FName, InStrRev(FName, "")) 'results in path
                End Function





                share|improve this answer






























                  up vote
                  0
                  down vote














                  Function file_name_only(file_path As String) As String

                  Dim temp As Variant

                  temp = Split(file_path, Application.PathSeparator)

                  file_name_only = temp(UBound(temp))

                  End Function



                  1. here you give your file name as input of the function

                  2. the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"

                  3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function


                  Hope this will be helpful.






                  share|improve this answer




























                    up vote
                    -1
                    down vote













                    Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
                    Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory





                    share|improve this answer





















                    • Although your answer may work for the question, could you please add some explanation of what is doing?
                      – Ivan
                      Aug 25 '15 at 12:00










                    • This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                      – user1054844
                      Nov 15 '16 at 9:25










                    • Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                      – ashleedawg
                      Apr 25 at 4:44











                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1743328%2fhow-to-extract-file-name-from-path%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    15 Answers
                    15






                    active

                    oldest

                    votes








                    15 Answers
                    15






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    up vote
                    37
                    down vote



                    accepted










                    This is taken from snippets.dzone.com:



                    Function GetFilenameFromPath(ByVal strPath As String) As String
                    ' Returns the rightmost characters of a string upto but not including the rightmost ''
                    ' e.g. 'c:winntwin.ini' returns 'win.ini'

                    If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
                    GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
                    End If
                    End Function





                    share|improve this answer

















                    • 1




                      Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                      – Thomas Fankhauser
                      Feb 24 '13 at 14:01






                    • 3




                      Just replace the in the code with a /.
                      – Gonzalo
                      Feb 25 '13 at 5:40






                    • 1




                      Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                      – Thomas Fankhauser
                      Feb 25 '13 at 17:07






                    • 3




                      This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                      – Mary
                      Jul 19 '13 at 18:58






                    • 4




                      IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                      – Matt
                      Jun 28 '15 at 21:33

















                    up vote
                    37
                    down vote



                    accepted










                    This is taken from snippets.dzone.com:



                    Function GetFilenameFromPath(ByVal strPath As String) As String
                    ' Returns the rightmost characters of a string upto but not including the rightmost ''
                    ' e.g. 'c:winntwin.ini' returns 'win.ini'

                    If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
                    GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
                    End If
                    End Function





                    share|improve this answer

















                    • 1




                      Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                      – Thomas Fankhauser
                      Feb 24 '13 at 14:01






                    • 3




                      Just replace the in the code with a /.
                      – Gonzalo
                      Feb 25 '13 at 5:40






                    • 1




                      Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                      – Thomas Fankhauser
                      Feb 25 '13 at 17:07






                    • 3




                      This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                      – Mary
                      Jul 19 '13 at 18:58






                    • 4




                      IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                      – Matt
                      Jun 28 '15 at 21:33















                    up vote
                    37
                    down vote



                    accepted







                    up vote
                    37
                    down vote



                    accepted






                    This is taken from snippets.dzone.com:



                    Function GetFilenameFromPath(ByVal strPath As String) As String
                    ' Returns the rightmost characters of a string upto but not including the rightmost ''
                    ' e.g. 'c:winntwin.ini' returns 'win.ini'

                    If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
                    GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
                    End If
                    End Function





                    share|improve this answer












                    This is taken from snippets.dzone.com:



                    Function GetFilenameFromPath(ByVal strPath As String) As String
                    ' Returns the rightmost characters of a string upto but not including the rightmost ''
                    ' e.g. 'c:winntwin.ini' returns 'win.ini'

                    If Right$(strPath, 1) <> "" And Len(strPath) > 0 Then
                    GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
                    End If
                    End Function






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '09 at 16:43









                    Gonzalo

                    17.3k35769




                    17.3k35769








                    • 1




                      Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                      – Thomas Fankhauser
                      Feb 24 '13 at 14:01






                    • 3




                      Just replace the in the code with a /.
                      – Gonzalo
                      Feb 25 '13 at 5:40






                    • 1




                      Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                      – Thomas Fankhauser
                      Feb 25 '13 at 17:07






                    • 3




                      This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                      – Mary
                      Jul 19 '13 at 18:58






                    • 4




                      IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                      – Matt
                      Jun 28 '15 at 21:33
















                    • 1




                      Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                      – Thomas Fankhauser
                      Feb 24 '13 at 14:01






                    • 3




                      Just replace the in the code with a /.
                      – Gonzalo
                      Feb 25 '13 at 5:40






                    • 1




                      Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                      – Thomas Fankhauser
                      Feb 25 '13 at 17:07






                    • 3




                      This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                      – Mary
                      Jul 19 '13 at 18:58






                    • 4




                      IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                      – Matt
                      Jun 28 '15 at 21:33










                    1




                    1




                    Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                    – Thomas Fankhauser
                    Feb 24 '13 at 14:01




                    Correct, but what if you're on a Mac? Unfortunately this is not a cross platform solution..
                    – Thomas Fankhauser
                    Feb 24 '13 at 14:01




                    3




                    3




                    Just replace the in the code with a /.
                    – Gonzalo
                    Feb 25 '13 at 5:40




                    Just replace the in the code with a /.
                    – Gonzalo
                    Feb 25 '13 at 5:40




                    1




                    1




                    Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                    – Thomas Fankhauser
                    Feb 25 '13 at 17:07




                    Then it's broken on windows, right? I already figured it out to use Application.PathSeparator, but unfortunately on OSX VBA even returns paths in the old :-notation. I had to write a function that converts those paths.
                    – Thomas Fankhauser
                    Feb 25 '13 at 17:07




                    3




                    3




                    This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                    – Mary
                    Jul 19 '13 at 18:58




                    This works, but is needlessly recursive, especially for VBA (which does not convert tail-recursion to a loop automatically).
                    – Mary
                    Jul 19 '13 at 18:58




                    4




                    4




                    IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                    – Matt
                    Jun 28 '15 at 21:33






                    IMHO, stackoverflow.com/a/1755577/481207 by Zen is a better answer. Code reuse, no recursion, no embedded constants.
                    – Matt
                    Jun 28 '15 at 21:33














                    up vote
                    109
                    down vote













                    The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).



                    Create a filesystem object and do all operations using that.



                    Dim fso as new FileSystemObject
                    Dim fileName As String
                    fileName = fso.GetFileName("c:any pathfile.txt")


                    The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.






                    share|improve this answer

















                    • 13




                      This answer beats the accepted answer by a mile.
                      – Bob Jansen
                      Dec 29 '14 at 8:28






                    • 6




                      In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                      – IceArdor
                      Apr 27 '15 at 23:46






                    • 3




                      A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                      – Ian Stanway
                      Nov 6 '15 at 12:21






                    • 2




                      @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:00






                    • 3




                      @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:05















                    up vote
                    109
                    down vote













                    The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).



                    Create a filesystem object and do all operations using that.



                    Dim fso as new FileSystemObject
                    Dim fileName As String
                    fileName = fso.GetFileName("c:any pathfile.txt")


                    The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.






                    share|improve this answer

















                    • 13




                      This answer beats the accepted answer by a mile.
                      – Bob Jansen
                      Dec 29 '14 at 8:28






                    • 6




                      In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                      – IceArdor
                      Apr 27 '15 at 23:46






                    • 3




                      A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                      – Ian Stanway
                      Nov 6 '15 at 12:21






                    • 2




                      @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:00






                    • 3




                      @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:05













                    up vote
                    109
                    down vote










                    up vote
                    109
                    down vote









                    The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).



                    Create a filesystem object and do all operations using that.



                    Dim fso as new FileSystemObject
                    Dim fileName As String
                    fileName = fso.GetFileName("c:any pathfile.txt")


                    The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.






                    share|improve this answer












                    The best way of working with files and directories in VBA for Office 2000/2003 is using the scripting library. Add a reference to Microsoft Scripting Runtime (Tools > References in the IDE).



                    Create a filesystem object and do all operations using that.



                    Dim fso as new FileSystemObject
                    Dim fileName As String
                    fileName = fso.GetFileName("c:any pathfile.txt")


                    The FileSystemObject is great. It offers a lot of features such as getting special folders (My documents, etc), creating, moving, copying, deleting files and directories in an object oriented manner. Check it out.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 18 '09 at 12:13









                    Zen

                    1,3143913




                    1,3143913








                    • 13




                      This answer beats the accepted answer by a mile.
                      – Bob Jansen
                      Dec 29 '14 at 8:28






                    • 6




                      In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                      – IceArdor
                      Apr 27 '15 at 23:46






                    • 3




                      A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                      – Ian Stanway
                      Nov 6 '15 at 12:21






                    • 2




                      @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:00






                    • 3




                      @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:05














                    • 13




                      This answer beats the accepted answer by a mile.
                      – Bob Jansen
                      Dec 29 '14 at 8:28






                    • 6




                      In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                      – IceArdor
                      Apr 27 '15 at 23:46






                    • 3




                      A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                      – Ian Stanway
                      Nov 6 '15 at 12:21






                    • 2




                      @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:00






                    • 3




                      @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                      – Mathieu Guindon
                      Jul 13 '17 at 20:05








                    13




                    13




                    This answer beats the accepted answer by a mile.
                    – Bob Jansen
                    Dec 29 '14 at 8:28




                    This answer beats the accepted answer by a mile.
                    – Bob Jansen
                    Dec 29 '14 at 8:28




                    6




                    6




                    In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                    – IceArdor
                    Apr 27 '15 at 23:46




                    In Excel VBA, Dim fileName As String; Dim fso as Object; Set fso = CreateObject("Scripting.FileSystemObject"); fileName = fso.GetFilename(path);
                    – IceArdor
                    Apr 27 '15 at 23:46




                    3




                    3




                    A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                    – Ian Stanway
                    Nov 6 '15 at 12:21




                    A word of warning, if you get a "User-defined type not defined" error you need to set a reference to the VB script run-time library. Load the VB Editor (ALT+F11), Select Tools > References from the drop-down menu, and from the list of available references tick the check box next to 'Microsoft Scripting Runtime' and click OK.
                    – Ian Stanway
                    Nov 6 '15 at 12:21




                    2




                    2




                    @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                    – Mathieu Guindon
                    Jul 13 '17 at 20:00




                    @Skrol29 every single Windows box in the world includes that library. Nothing to worry about. Accepted answer won't work on a Mac either. People that systematically late-bind the Scripting runtime don't know what they're doing, nor why. This answer is perfectly acceptable, and does beat the accepted answer by a mile. Or two.
                    – Mathieu Guindon
                    Jul 13 '17 at 20:00




                    3




                    3




                    @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                    – Mathieu Guindon
                    Jul 13 '17 at 20:05




                    @IceArdor Late-binding the Scripting Runtime buys you exactly nothing. You get a performance penalty for resolving the calls at run-time, and zero compile-time checks which means you make a typo and you won't know about it until you run the code, which will happily compile. Don't late-bind a library that's standard delivery on every single Windows machine since Win98.
                    – Mathieu Guindon
                    Jul 13 '17 at 20:05










                    up vote
                    41
                    down vote













                    Dir("C:Documentsmyfile.pdf")


                    will return the file name, but only if it exists.






                    share|improve this answer



















                    • 1




                      +1 for "really short"
                      – golimar
                      Nov 13 '14 at 10:07






                    • 3




                      Bad because it assumes that the path is for a physical file that the program can read.
                      – Skrol29
                      Nov 6 '15 at 15:41










                    • hi @Skrol29, could you please help to explain more on this?
                      – Harry Duong
                      Dec 17 '15 at 0:21










                    • @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                      – Dick Kusleika
                      Dec 17 '15 at 16:48










                    • @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                      – Skrol29
                      Dec 22 '15 at 16:08

















                    up vote
                    41
                    down vote













                    Dir("C:Documentsmyfile.pdf")


                    will return the file name, but only if it exists.






                    share|improve this answer



















                    • 1




                      +1 for "really short"
                      – golimar
                      Nov 13 '14 at 10:07






                    • 3




                      Bad because it assumes that the path is for a physical file that the program can read.
                      – Skrol29
                      Nov 6 '15 at 15:41










                    • hi @Skrol29, could you please help to explain more on this?
                      – Harry Duong
                      Dec 17 '15 at 0:21










                    • @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                      – Dick Kusleika
                      Dec 17 '15 at 16:48










                    • @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                      – Skrol29
                      Dec 22 '15 at 16:08















                    up vote
                    41
                    down vote










                    up vote
                    41
                    down vote









                    Dir("C:Documentsmyfile.pdf")


                    will return the file name, but only if it exists.






                    share|improve this answer














                    Dir("C:Documentsmyfile.pdf")


                    will return the file name, but only if it exists.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Oct 5 '13 at 13:29

























                    answered Nov 22 '09 at 13:53









                    Dick Kusleika

                    27.3k33559




                    27.3k33559








                    • 1




                      +1 for "really short"
                      – golimar
                      Nov 13 '14 at 10:07






                    • 3




                      Bad because it assumes that the path is for a physical file that the program can read.
                      – Skrol29
                      Nov 6 '15 at 15:41










                    • hi @Skrol29, could you please help to explain more on this?
                      – Harry Duong
                      Dec 17 '15 at 0:21










                    • @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                      – Dick Kusleika
                      Dec 17 '15 at 16:48










                    • @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                      – Skrol29
                      Dec 22 '15 at 16:08
















                    • 1




                      +1 for "really short"
                      – golimar
                      Nov 13 '14 at 10:07






                    • 3




                      Bad because it assumes that the path is for a physical file that the program can read.
                      – Skrol29
                      Nov 6 '15 at 15:41










                    • hi @Skrol29, could you please help to explain more on this?
                      – Harry Duong
                      Dec 17 '15 at 0:21










                    • @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                      – Dick Kusleika
                      Dec 17 '15 at 16:48










                    • @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                      – Skrol29
                      Dec 22 '15 at 16:08










                    1




                    1




                    +1 for "really short"
                    – golimar
                    Nov 13 '14 at 10:07




                    +1 for "really short"
                    – golimar
                    Nov 13 '14 at 10:07




                    3




                    3




                    Bad because it assumes that the path is for a physical file that the program can read.
                    – Skrol29
                    Nov 6 '15 at 15:41




                    Bad because it assumes that the path is for a physical file that the program can read.
                    – Skrol29
                    Nov 6 '15 at 15:41












                    hi @Skrol29, could you please help to explain more on this?
                    – Harry Duong
                    Dec 17 '15 at 0:21




                    hi @Skrol29, could you please help to explain more on this?
                    – Harry Duong
                    Dec 17 '15 at 0:21












                    @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                    – Dick Kusleika
                    Dec 17 '15 at 16:48




                    @HarryDuong Dir returns the file name, but only if the file actually exists at that location. If the file does not exist, Dir return an empty string. If you know the file exists, such as when you prompt the user to select a file, then this is a quick and easy way to get the file name. If you don't know whether the file exists, Split from @ArturPiwkowski is better. Two Splits will be faster than any string manipulation.
                    – Dick Kusleika
                    Dec 17 '15 at 16:48












                    @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                    – Skrol29
                    Dec 22 '15 at 16:08






                    @Harry Duong: The function Dir() does perform a scan on the computer to check the given mask. In this examples, the mask is the name of the expected file. If the file does not exist on the computer, the Dir() returns an empty value. But here is many cases when you what to extract the name from a path that does not physically exists. For example for a path of a file to be created, or a file just deleted before.
                    – Skrol29
                    Dec 22 '15 at 16:08












                    up vote
                    24
                    down vote













                    I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.



                    Function FileNameFromPath(strFullPath As String) As String

                    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))

                    End Function


                    http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.






                    share|improve this answer

















                    • 1




                      The best for me : smart, short and does off-road.
                      – Skrol29
                      Nov 6 '15 at 15:51






                    • 2




                      +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                      – tahwos
                      Oct 3 '16 at 3:45










                    • I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                      – mattlore
                      Sep 13 '17 at 17:53















                    up vote
                    24
                    down vote













                    I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.



                    Function FileNameFromPath(strFullPath As String) As String

                    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))

                    End Function


                    http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.






                    share|improve this answer

















                    • 1




                      The best for me : smart, short and does off-road.
                      – Skrol29
                      Nov 6 '15 at 15:51






                    • 2




                      +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                      – tahwos
                      Oct 3 '16 at 3:45










                    • I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                      – mattlore
                      Sep 13 '17 at 17:53













                    up vote
                    24
                    down vote










                    up vote
                    24
                    down vote









                    I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.



                    Function FileNameFromPath(strFullPath As String) As String

                    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))

                    End Function


                    http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.






                    share|improve this answer












                    I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.



                    Function FileNameFromPath(strFullPath As String) As String

                    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, ""))

                    End Function


                    http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 5 '13 at 1:01









                    user2780436

                    37429




                    37429








                    • 1




                      The best for me : smart, short and does off-road.
                      – Skrol29
                      Nov 6 '15 at 15:51






                    • 2




                      +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                      – tahwos
                      Oct 3 '16 at 3:45










                    • I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                      – mattlore
                      Sep 13 '17 at 17:53














                    • 1




                      The best for me : smart, short and does off-road.
                      – Skrol29
                      Nov 6 '15 at 15:51






                    • 2




                      +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                      – tahwos
                      Oct 3 '16 at 3:45










                    • I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                      – mattlore
                      Sep 13 '17 at 17:53








                    1




                    1




                    The best for me : smart, short and does off-road.
                    – Skrol29
                    Nov 6 '15 at 15:51




                    The best for me : smart, short and does off-road.
                    – Skrol29
                    Nov 6 '15 at 15:51




                    2




                    2




                    +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                    – tahwos
                    Oct 3 '16 at 3:45




                    +1 for simplicity - can even forego the function, and use the "=" line as-is, or in a loop, for multiple files.
                    – tahwos
                    Oct 3 '16 at 3:45












                    I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                    – mattlore
                    Sep 13 '17 at 17:53




                    I prefer this one over any of the other answers. It's easily reusable in any other sub or function and doesn't require any fiddling with references
                    – mattlore
                    Sep 13 '17 at 17:53










                    up vote
                    9
                    down vote













                    Dim sFilePath$, sFileName$
                    sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))





                    share|improve this answer























                    • Not so smart because it run twice Split(sFilePath, "").
                      – Skrol29
                      Nov 6 '15 at 15:39















                    up vote
                    9
                    down vote













                    Dim sFilePath$, sFileName$
                    sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))





                    share|improve this answer























                    • Not so smart because it run twice Split(sFilePath, "").
                      – Skrol29
                      Nov 6 '15 at 15:39













                    up vote
                    9
                    down vote










                    up vote
                    9
                    down vote









                    Dim sFilePath$, sFileName$
                    sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))





                    share|improve this answer














                    Dim sFilePath$, sFileName$
                    sFileName = Split(sFilePath, "")(UBound(Split(sFilePath, "")))






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 8 '13 at 15:42









                    Jon Egerton

                    29.5k1070112




                    29.5k1070112










                    answered Feb 8 '13 at 15:24









                    Artur Piwkowski

                    9911




                    9911












                    • Not so smart because it run twice Split(sFilePath, "").
                      – Skrol29
                      Nov 6 '15 at 15:39


















                    • Not so smart because it run twice Split(sFilePath, "").
                      – Skrol29
                      Nov 6 '15 at 15:39
















                    Not so smart because it run twice Split(sFilePath, "").
                    – Skrol29
                    Nov 6 '15 at 15:39




                    Not so smart because it run twice Split(sFilePath, "").
                    – Skrol29
                    Nov 6 '15 at 15:39










                    up vote
                    4
                    down vote













                    If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:



                    Dim strFileName As String, strFolderPath As String
                    Dim lngIndex As Long
                    Dim strPath() As String

                    strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
                    lngIndex = UBound(strPath)
                    strFileName = strPath(lngIndex) 'Get the File Name from our array
                    strPath(lngIndex) = "" 'Remove the File Name from our array
                    strFolderPath = Join(strPath, "") 'Rebuild our path from our array


                    Or as a sub/function:



                    Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)    
                    Dim strPath() As String
                    Dim lngIndex As Long

                    strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
                    lngIndex = UBound(strPath)
                    o_strFileName = strPath(lngIndex) 'Get the File Name from our array
                    strPath(lngIndex) = "" 'Remove the File Name from our array
                    io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
                    End Sub


                    You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.






                    share|improve this answer

























                      up vote
                      4
                      down vote













                      If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:



                      Dim strFileName As String, strFolderPath As String
                      Dim lngIndex As Long
                      Dim strPath() As String

                      strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
                      lngIndex = UBound(strPath)
                      strFileName = strPath(lngIndex) 'Get the File Name from our array
                      strPath(lngIndex) = "" 'Remove the File Name from our array
                      strFolderPath = Join(strPath, "") 'Rebuild our path from our array


                      Or as a sub/function:



                      Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)    
                      Dim strPath() As String
                      Dim lngIndex As Long

                      strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
                      lngIndex = UBound(strPath)
                      o_strFileName = strPath(lngIndex) 'Get the File Name from our array
                      strPath(lngIndex) = "" 'Remove the File Name from our array
                      io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
                      End Sub


                      You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.






                      share|improve this answer























                        up vote
                        4
                        down vote










                        up vote
                        4
                        down vote









                        If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:



                        Dim strFileName As String, strFolderPath As String
                        Dim lngIndex As Long
                        Dim strPath() As String

                        strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
                        lngIndex = UBound(strPath)
                        strFileName = strPath(lngIndex) 'Get the File Name from our array
                        strPath(lngIndex) = "" 'Remove the File Name from our array
                        strFolderPath = Join(strPath, "") 'Rebuild our path from our array


                        Or as a sub/function:



                        Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)    
                        Dim strPath() As String
                        Dim lngIndex As Long

                        strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
                        lngIndex = UBound(strPath)
                        o_strFileName = strPath(lngIndex) 'Get the File Name from our array
                        strPath(lngIndex) = "" 'Remove the File Name from our array
                        io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
                        End Sub


                        You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.






                        share|improve this answer












                        If you want a more robust solution that will give you both the full folder's path AND the filename, here it is:



                        Dim strFileName As String, strFolderPath As String
                        Dim lngIndex As Long
                        Dim strPath() As String

                        strPath() = Split(OpenArgs, "") 'Put the Parts of our path into an array
                        lngIndex = UBound(strPath)
                        strFileName = strPath(lngIndex) 'Get the File Name from our array
                        strPath(lngIndex) = "" 'Remove the File Name from our array
                        strFolderPath = Join(strPath, "") 'Rebuild our path from our array


                        Or as a sub/function:



                        Private Sub SeparatePathAndFile(ByRef io_strFolderPath As String, ByRef o_strFileName As String)    
                        Dim strPath() As String
                        Dim lngIndex As Long

                        strPath() = Split(io_strFolderPath, "") 'Put the Parts of our path into an array
                        lngIndex = UBound(strPath)
                        o_strFileName = strPath(lngIndex) 'Get the File Name from our array
                        strPath(lngIndex) = "" 'Remove the File Name from our array
                        io_strFolderPath = Join(strPath, "") 'Rebuild our path from our array
                        End Sub


                        You pass the first parameter with the full path of the file and it will be set to the folder's path while the second parameter will be set to the file's name.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 4 '12 at 17:15









                        dnLL

                        1,949113871




                        1,949113871






















                            up vote
                            3
                            down vote













                            To get the file name in an excel macro is:



                            filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
                            MsgBox Mid(filname, 1, InStr(filname, ".") - 1)





                            share|improve this answer



























                              up vote
                              3
                              down vote













                              To get the file name in an excel macro is:



                              filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
                              MsgBox Mid(filname, 1, InStr(filname, ".") - 1)





                              share|improve this answer

























                                up vote
                                3
                                down vote










                                up vote
                                3
                                down vote









                                To get the file name in an excel macro is:



                                filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
                                MsgBox Mid(filname, 1, InStr(filname, ".") - 1)





                                share|improve this answer














                                To get the file name in an excel macro is:



                                filname = Mid(spth, InStrRev(spth, "", Len(spth)) + 1, Len(spth))
                                MsgBox Mid(filname, 1, InStr(filname, ".") - 1)






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Sep 26 '12 at 11:26









                                Florent

                                10.7k74153




                                10.7k74153










                                answered Sep 19 '12 at 14:17









                                niki

                                311




                                311






















                                    up vote
                                    3
                                    down vote













                                    I can't believe how overcomplicated some of these answers are... (no offence!)



                                    Here's a single-line function that will get the job done:





                                    **Extract Filename from <code>x:pathfilename</code>:**



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




                                    **Extract Path from <code>x:pathfilename</code>:**



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




                                    Examples:



                                    examples






                                    share|improve this answer

























                                      up vote
                                      3
                                      down vote













                                      I can't believe how overcomplicated some of these answers are... (no offence!)



                                      Here's a single-line function that will get the job done:





                                      **Extract Filename from <code>x:pathfilename</code>:**



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




                                      **Extract Path from <code>x:pathfilename</code>:**



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




                                      Examples:



                                      examples






                                      share|improve this answer























                                        up vote
                                        3
                                        down vote










                                        up vote
                                        3
                                        down vote









                                        I can't believe how overcomplicated some of these answers are... (no offence!)



                                        Here's a single-line function that will get the job done:





                                        **Extract Filename from <code>x:pathfilename</code>:**



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




                                        **Extract Path from <code>x:pathfilename</code>:**



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




                                        Examples:



                                        examples






                                        share|improve this answer












                                        I can't believe how overcomplicated some of these answers are... (no offence!)



                                        Here's a single-line function that will get the job done:





                                        **Extract Filename from <code>x:pathfilename</code>:**



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




                                        **Extract Path from <code>x:pathfilename</code>:**



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




                                        Examples:



                                        examples







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Apr 25 at 4:40









                                        ashleedawg

                                        12.5k41848




                                        12.5k41848






















                                            up vote
                                            2
                                            down vote













                                            Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.



                                            sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)

                                            sFolderName = Left(sPath, Len(sPath) - Len(sFileName))


                                            You can test the output using this code:



                                            'Visual Basic for Applications 
                                            http = "https://www.server.com/docs/Letter.txt"
                                            unix = "/home/user/docs/Letter.txt"
                                            dos = "C:userdocsLetter.txt"
                                            win = "\Server01userdocsLetter.txt"
                                            blank = ""

                                            sPath = unix
                                            sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
                                            sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

                                            Debug.print "Folder: " & sFolderName & " File: " & sFileName


                                            Also see: Wikipedia - Path (computing)






                                            share|improve this answer

























                                              up vote
                                              2
                                              down vote













                                              Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.



                                              sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)

                                              sFolderName = Left(sPath, Len(sPath) - Len(sFileName))


                                              You can test the output using this code:



                                              'Visual Basic for Applications 
                                              http = "https://www.server.com/docs/Letter.txt"
                                              unix = "/home/user/docs/Letter.txt"
                                              dos = "C:userdocsLetter.txt"
                                              win = "\Server01userdocsLetter.txt"
                                              blank = ""

                                              sPath = unix
                                              sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
                                              sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

                                              Debug.print "Folder: " & sFolderName & " File: " & sFileName


                                              Also see: Wikipedia - Path (computing)






                                              share|improve this answer























                                                up vote
                                                2
                                                down vote










                                                up vote
                                                2
                                                down vote









                                                Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.



                                                sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)

                                                sFolderName = Left(sPath, Len(sPath) - Len(sFileName))


                                                You can test the output using this code:



                                                'Visual Basic for Applications 
                                                http = "https://www.server.com/docs/Letter.txt"
                                                unix = "/home/user/docs/Letter.txt"
                                                dos = "C:userdocsLetter.txt"
                                                win = "\Server01userdocsLetter.txt"
                                                blank = ""

                                                sPath = unix
                                                sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
                                                sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

                                                Debug.print "Folder: " & sFolderName & " File: " & sFileName


                                                Also see: Wikipedia - Path (computing)






                                                share|improve this answer












                                                Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.



                                                sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)

                                                sFolderName = Left(sPath, Len(sPath) - Len(sFileName))


                                                You can test the output using this code:



                                                'Visual Basic for Applications 
                                                http = "https://www.server.com/docs/Letter.txt"
                                                unix = "/home/user/docs/Letter.txt"
                                                dos = "C:userdocsLetter.txt"
                                                win = "\Server01userdocsLetter.txt"
                                                blank = ""

                                                sPath = unix
                                                sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "") + 1)
                                                sFolderName = Left(sPath, Len(sPath) - Len(sFileName))

                                                Debug.print "Folder: " & sFolderName & " File: " & sFileName


                                                Also see: Wikipedia - Path (computing)







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Oct 13 '13 at 16:58









                                                Roberto

                                                2,75611218




                                                2,75611218






















                                                    up vote
                                                    2
                                                    down vote













                                                    The simplest approach if you are sure the file physically exists on the disk:



                                                    Dim fileName, filePath As String
                                                    filePath = "C:Documentsmyfile.pdf"
                                                    fileName = Dir(filePath)


                                                    If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:



                                                    fileName = Mid(filePath, InStrRev(filePath, "") + 1)





                                                    share|improve this answer

























                                                      up vote
                                                      2
                                                      down vote













                                                      The simplest approach if you are sure the file physically exists on the disk:



                                                      Dim fileName, filePath As String
                                                      filePath = "C:Documentsmyfile.pdf"
                                                      fileName = Dir(filePath)


                                                      If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:



                                                      fileName = Mid(filePath, InStrRev(filePath, "") + 1)





                                                      share|improve this answer























                                                        up vote
                                                        2
                                                        down vote










                                                        up vote
                                                        2
                                                        down vote









                                                        The simplest approach if you are sure the file physically exists on the disk:



                                                        Dim fileName, filePath As String
                                                        filePath = "C:Documentsmyfile.pdf"
                                                        fileName = Dir(filePath)


                                                        If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:



                                                        fileName = Mid(filePath, InStrRev(filePath, "") + 1)





                                                        share|improve this answer












                                                        The simplest approach if you are sure the file physically exists on the disk:



                                                        Dim fileName, filePath As String
                                                        filePath = "C:Documentsmyfile.pdf"
                                                        fileName = Dir(filePath)


                                                        If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:



                                                        fileName = Mid(filePath, InStrRev(filePath, "") + 1)






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Mar 23 '17 at 5:46









                                                        ePandit

                                                        1,37811311




                                                        1,37811311






















                                                            up vote
                                                            1
                                                            down vote













                                                            Here's an alternative solution without code. This VBA works in the Excel Formula Bar:



                                                            To extract the file name:



                                                            =RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"","~",LEN(A1)-LEN(SUBSTITUTE(A1,"","")))))


                                                            To extract the file path:



                                                            =MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"",""))))+1,LEN(A1))))





                                                            share|improve this answer



























                                                              up vote
                                                              1
                                                              down vote













                                                              Here's an alternative solution without code. This VBA works in the Excel Formula Bar:



                                                              To extract the file name:



                                                              =RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"","~",LEN(A1)-LEN(SUBSTITUTE(A1,"","")))))


                                                              To extract the file path:



                                                              =MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"",""))))+1,LEN(A1))))





                                                              share|improve this answer

























                                                                up vote
                                                                1
                                                                down vote










                                                                up vote
                                                                1
                                                                down vote









                                                                Here's an alternative solution without code. This VBA works in the Excel Formula Bar:



                                                                To extract the file name:



                                                                =RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"","~",LEN(A1)-LEN(SUBSTITUTE(A1,"","")))))


                                                                To extract the file path:



                                                                =MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"",""))))+1,LEN(A1))))





                                                                share|improve this answer














                                                                Here's an alternative solution without code. This VBA works in the Excel Formula Bar:



                                                                To extract the file name:



                                                                =RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"","~",LEN(A1)-LEN(SUBSTITUTE(A1,"","")))))


                                                                To extract the file path:



                                                                =MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"",""))))+1,LEN(A1))))






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Mar 4 '14 at 20:39

























                                                                answered Aug 23 '13 at 14:32









                                                                live-love

                                                                15.5k87971




                                                                15.5k87971






















                                                                    up vote
                                                                    0
                                                                    down vote













                                                                    I needed the path, not the filename.



                                                                    So to extract the file path in code:



                                                                    JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, ""))))) 





                                                                    share|improve this answer



























                                                                      up vote
                                                                      0
                                                                      down vote













                                                                      I needed the path, not the filename.



                                                                      So to extract the file path in code:



                                                                      JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, ""))))) 





                                                                      share|improve this answer

























                                                                        up vote
                                                                        0
                                                                        down vote










                                                                        up vote
                                                                        0
                                                                        down vote









                                                                        I needed the path, not the filename.



                                                                        So to extract the file path in code:



                                                                        JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, ""))))) 





                                                                        share|improve this answer














                                                                        I needed the path, not the filename.



                                                                        So to extract the file path in code:



                                                                        JustPath = Left(sFileP, Len(sFileP) - Len(Split(sFileP, "")(UBound(Split(sFileP, ""))))) 






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Oct 3 '13 at 18:38









                                                                        Darwind

                                                                        5,77933443




                                                                        5,77933443










                                                                        answered Oct 3 '13 at 18:08









                                                                        Doug

                                                                        1




                                                                        1






















                                                                            up vote
                                                                            0
                                                                            down vote













                                                                            This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:



                                                                            'since the file name and path were used several times in code
                                                                            'variables were made public

                                                                            Public FName As Variant, Filename As String, Path As String

                                                                            Sub xxx()
                                                                            ...
                                                                            If Not GetFileName = 1 Then Exit Sub '
                                                                            ...
                                                                            End Sub

                                                                            Private Function GetFileName()
                                                                            GetFileName = 0 'used for error handling at call point in case user cancels
                                                                            FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
                                                                            If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
                                                                            Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
                                                                            Path = Left(FName, InStrRev(FName, "")) 'results in path
                                                                            End Function





                                                                            share|improve this answer



























                                                                              up vote
                                                                              0
                                                                              down vote













                                                                              This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:



                                                                              'since the file name and path were used several times in code
                                                                              'variables were made public

                                                                              Public FName As Variant, Filename As String, Path As String

                                                                              Sub xxx()
                                                                              ...
                                                                              If Not GetFileName = 1 Then Exit Sub '
                                                                              ...
                                                                              End Sub

                                                                              Private Function GetFileName()
                                                                              GetFileName = 0 'used for error handling at call point in case user cancels
                                                                              FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
                                                                              If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
                                                                              Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
                                                                              Path = Left(FName, InStrRev(FName, "")) 'results in path
                                                                              End Function





                                                                              share|improve this answer

























                                                                                up vote
                                                                                0
                                                                                down vote










                                                                                up vote
                                                                                0
                                                                                down vote









                                                                                This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:



                                                                                'since the file name and path were used several times in code
                                                                                'variables were made public

                                                                                Public FName As Variant, Filename As String, Path As String

                                                                                Sub xxx()
                                                                                ...
                                                                                If Not GetFileName = 1 Then Exit Sub '
                                                                                ...
                                                                                End Sub

                                                                                Private Function GetFileName()
                                                                                GetFileName = 0 'used for error handling at call point in case user cancels
                                                                                FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
                                                                                If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
                                                                                Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
                                                                                Path = Left(FName, InStrRev(FName, "")) 'results in path
                                                                                End Function





                                                                                share|improve this answer














                                                                                This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:



                                                                                'since the file name and path were used several times in code
                                                                                'variables were made public

                                                                                Public FName As Variant, Filename As String, Path As String

                                                                                Sub xxx()
                                                                                ...
                                                                                If Not GetFileName = 1 Then Exit Sub '
                                                                                ...
                                                                                End Sub

                                                                                Private Function GetFileName()
                                                                                GetFileName = 0 'used for error handling at call point in case user cancels
                                                                                FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
                                                                                If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
                                                                                Filename = Split(FName, "")(UBound(Split(FName, ""))) 'results in file name
                                                                                Path = Left(FName, InStrRev(FName, "")) 'results in path
                                                                                End Function






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Oct 3 '14 at 6:47

























                                                                                answered Oct 3 '14 at 6:41









                                                                                Dan

                                                                                63




                                                                                63






















                                                                                    up vote
                                                                                    0
                                                                                    down vote














                                                                                    Function file_name_only(file_path As String) As String

                                                                                    Dim temp As Variant

                                                                                    temp = Split(file_path, Application.PathSeparator)

                                                                                    file_name_only = temp(UBound(temp))

                                                                                    End Function



                                                                                    1. here you give your file name as input of the function

                                                                                    2. the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"

                                                                                    3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function


                                                                                    Hope this will be helpful.






                                                                                    share|improve this answer

























                                                                                      up vote
                                                                                      0
                                                                                      down vote














                                                                                      Function file_name_only(file_path As String) As String

                                                                                      Dim temp As Variant

                                                                                      temp = Split(file_path, Application.PathSeparator)

                                                                                      file_name_only = temp(UBound(temp))

                                                                                      End Function



                                                                                      1. here you give your file name as input of the function

                                                                                      2. the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"

                                                                                      3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function


                                                                                      Hope this will be helpful.






                                                                                      share|improve this answer























                                                                                        up vote
                                                                                        0
                                                                                        down vote










                                                                                        up vote
                                                                                        0
                                                                                        down vote










                                                                                        Function file_name_only(file_path As String) As String

                                                                                        Dim temp As Variant

                                                                                        temp = Split(file_path, Application.PathSeparator)

                                                                                        file_name_only = temp(UBound(temp))

                                                                                        End Function



                                                                                        1. here you give your file name as input of the function

                                                                                        2. the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"

                                                                                        3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function


                                                                                        Hope this will be helpful.






                                                                                        share|improve this answer













                                                                                        Function file_name_only(file_path As String) As String

                                                                                        Dim temp As Variant

                                                                                        temp = Split(file_path, Application.PathSeparator)

                                                                                        file_name_only = temp(UBound(temp))

                                                                                        End Function



                                                                                        1. here you give your file name as input of the function

                                                                                        2. the split function of VBA splits the path in different portion by using "" as path separator & stores them in an array named "temp"

                                                                                        3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function


                                                                                        Hope this will be helpful.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Nov 11 at 10:42









                                                                                        mishu36

                                                                                        11




                                                                                        11






















                                                                                            up vote
                                                                                            -1
                                                                                            down vote













                                                                                            Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
                                                                                            Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory





                                                                                            share|improve this answer





















                                                                                            • Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                              – Ivan
                                                                                              Aug 25 '15 at 12:00










                                                                                            • This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                              – user1054844
                                                                                              Nov 15 '16 at 9:25










                                                                                            • Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                              – ashleedawg
                                                                                              Apr 25 at 4:44















                                                                                            up vote
                                                                                            -1
                                                                                            down vote













                                                                                            Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
                                                                                            Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory





                                                                                            share|improve this answer





















                                                                                            • Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                              – Ivan
                                                                                              Aug 25 '15 at 12:00










                                                                                            • This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                              – user1054844
                                                                                              Nov 15 '16 at 9:25










                                                                                            • Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                              – ashleedawg
                                                                                              Apr 25 at 4:44













                                                                                            up vote
                                                                                            -1
                                                                                            down vote










                                                                                            up vote
                                                                                            -1
                                                                                            down vote









                                                                                            Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
                                                                                            Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory





                                                                                            share|improve this answer












                                                                                            Dim nme As String = My.Computer.FileSystem.GetFileInfo(pathFicheiro).Name
                                                                                            Dim dirc As String = My.Computer.FileSystem.GetFileInfo(nomeFicheiro).Directory






                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered Aug 25 '15 at 9:36









                                                                                            Paulos02

                                                                                            12614




                                                                                            12614












                                                                                            • Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                              – Ivan
                                                                                              Aug 25 '15 at 12:00










                                                                                            • This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                              – user1054844
                                                                                              Nov 15 '16 at 9:25










                                                                                            • Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                              – ashleedawg
                                                                                              Apr 25 at 4:44


















                                                                                            • Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                              – Ivan
                                                                                              Aug 25 '15 at 12:00










                                                                                            • This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                              – user1054844
                                                                                              Nov 15 '16 at 9:25










                                                                                            • Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                              – ashleedawg
                                                                                              Apr 25 at 4:44
















                                                                                            Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                            – Ivan
                                                                                            Aug 25 '15 at 12:00




                                                                                            Although your answer may work for the question, could you please add some explanation of what is doing?
                                                                                            – Ivan
                                                                                            Aug 25 '15 at 12:00












                                                                                            This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                            – user1054844
                                                                                            Nov 15 '16 at 9:25




                                                                                            This is better solution. It extracs filename and directory from given path pathFicheiro. There is no need for nomeFicheiro as you could just use pathFicheiro. pathFicheiro = FILENAME variable
                                                                                            – user1054844
                                                                                            Nov 15 '16 at 9:25












                                                                                            Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                            – ashleedawg
                                                                                            Apr 25 at 4:44




                                                                                            Sorry but unless I'm missing something, this is .net, so it doesn't answer the vba question.
                                                                                            – ashleedawg
                                                                                            Apr 25 at 4:44


















                                                                                            draft saved

                                                                                            draft discarded




















































                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                            But avoid



                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                            To learn more, see our tips on writing great answers.





                                                                                            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                            Please pay close attention to the following guidance:


                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                            But avoid



                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                            To learn more, see our tips on writing great answers.




                                                                                            draft saved


                                                                                            draft discarded














                                                                                            StackExchange.ready(
                                                                                            function () {
                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1743328%2fhow-to-extract-file-name-from-path%23new-answer', 'question_page');
                                                                                            }
                                                                                            );

                                                                                            Post as a guest















                                                                                            Required, but never shown





















































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown

































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown







                                                                                            Popular posts from this blog

                                                                                            Bressuire

                                                                                            Vorschmack

                                                                                            Quarantine