Friday, February 13, 2015

Parsing a File String Into Path, File Name, and Extension

http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/

Sample 1: Extract a File name that includes the file extension
?
1
2
3
4
5
Function FileNameFromPath(strFullPath As String) As String
 
     FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
 
End Function

Sample 2: Extract a File name that does not include the file extension
?
1
2
3
4
5
6
7
8
9
10
11
12
13
Function FileNameNoExtensionFromPath(strFullPath As String) As String
 
    Dim intStartLoc As Integer
    Dim intEndLoc As Integer
    Dim intLength As Integer
 
    intStartLoc = Len(strFullPath) - (Len(strFullPath) - InStrRev(strFullPath, "\") - 1)
    intEndLoc = Len(strFullPath) - (Len(strFullPath) - InStrRev(strFullPath, "."))
    intLength = intEndLoc - intStartLoc
 
    FileNameNoExtensionFromPath = Mid(strFullPath, intStartLoc, intLength)
 
End Function

Sample 3: Extract a path to the containing folder (last character is a slash)
?
1
2
3
4
5
Function FolderFromPath(ByRef strFullPath As String) As String
 
     FolderFromPath = Left(strFullPath, InStrRev(strFullPath, "\"))
 
End Function

Sample 4: Extract a file extension (no dot)
?
1
2
3
4
5
Function FileExtensionFromPath(ByRef strFullPath As String) As String
 
     FileExtensionFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "."))
 
End Function

No comments: