[英]Excel VBA: How to extract specific folder from file path
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.
例如,假设我的文件路径为“ C:\\ Users \\ Desktop \\ Programs \\ Training Log \\ Folder Database”,而我只想提取“ Training”文件夹并另存为变量。 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. 您可以使用
Split
获得第4部分。
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. 通过使用
Optional
,默认值为0,因此您可以将其用作单参数或二参数函数。 The level
argument lets you choose how many levels (directories) deep you go. level
参数使您可以选择要深入的级别(目录)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.