Applecore Pages on Microsoft Access

Getting the Name of a File from the Name and Path

If you want to get just the name of a file, given the path and name of it, i.e. from C:\FolderName\FileName.txt you are just interested in FileName.txt, then there are three different ways of doing this.

Firstly, if the file exists on the computer, then you can just use the Dir function, as below:

?Dir("C:\Folder\FileName.txt")

If however, the file does not exist on the computer, the above code will return a zero length string. Instead you will need to use a function such as the one below:

Public Function fGetFileName(ByVal strPath As String) As String
'   Procedure to get the name of a file from the full name and path supplied
'   Accepts:
'       strPath - the full name and path of the file
'   Returns:
'       Just the name of the file

    On Error GoTo E_Handle
    Do While InStr(strPath, "\") > 0
        strPath = Mid(strPath, InStr(strPath, "\") + 1)
    Loop
    fGetFileName = strPath
fExit:
    On Error Resume Next
    Exit Function
E_Handle:
    MsgBox Err.Description & vbCrLf & "fGetFileName", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume fExit
End Function

Finally, if you are using Access 2000 or later, then you can use InStrRev to get the position of the last '\' in the path, and use Mid to get the file name:

?Mid("C:\Folder\FileName.txt",InStrRev("C:\Folder\FileName.txt","\")+1)

Top

 


HOME | NEW | TABLES | QUERIES | FORMS | REPORTS | GENERAL | API | DOWNLOADS | TUTORIAL | RESOURCES
E-MAIL
Copyright & Disclaimer

 

Last modified at 06/06/2006 14:57:19