I'm looking for a function that will return the fourth file within a file path. For example, say my file path is "C:\\Users\\Desktop\\Programs\\Training Log\\Folder Database" and I would like to extract just the "Training" folder and save as variable. How could I go about doing that?
Here is my current function:
Function GetFilenameFromPath(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
This function just returns the immediate parent folder. How could I tweak it to specify a folder other than the immediate parent.
Thanks!!
You can use Split
to get the 4th part.
Sub Sample()
Dim FilePath As String
Dim MyAr As Variant
FilePath = "C:\Users\Desktop\Programs\Training Log\Folder Database"
MyAr = Split(FilePath, "\")
Debug.Print MyAr(4)
End Sub
You can accomplish this using this function:
Public Function getParentFolder(path As String, Optional level As Integer = 0)
Dim pathTokens() As String
pathTokens = VBA.split(path, "\")
Debug.Assert level >= 0 And level <= UBound(pathTokens)
getParentFolder = pathTokens(UBound(pathTokens) - level)
End Function
By using Optional
the default value is 0, so you can use this as a single- or two-argument function. The level
argument lets you choose how many levels (directories) deep you go.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.