VBA - 从路径中提取特定文件夹名称
VBA - Extract Particular Folder Name from Path
我有以下代码,但我需要调整。我希望用户从项目中 select 一个特定的文件夹。想象路径 "C:\Project\SomeOtherFolder\WINDOW"。如果 select 编辑了 "WINDOW" 文件夹,下面的代码只会填充文本框。我只是用它来检查用户,但实际上我希望文本框填充 "Project".
Using fb As New FolderBrowserDialog
If fb.ShowDialog = Windows.Forms.DialogResult.OK AndAlso _
(IO.Path.GetFileName(fb.SelectedPath) = "WINDOW") Then
TextBox1.Text = IO.Path.GetFileName(fb.SelectedPath)
Else
Exit Sub
End If
End Using
请问我怎样才能做到这一点?非常感谢!!!
这个 UDF,应该能满足您的需求。我创建了从特定文件夹位置 return 文件夹名称的函数。我已经包含了一些可选参数,因此您可以(如果需要)更改要求。
Public Function GetFolderName(FolderPath As String, _
Optional endPath As String = "WINDOW", _
Optional moveUp As Integer = 2) As String
Dim tmpArr() As String, retStr As String
tmpArr = Split(FolderPath, "\")
If InStr(FolderPath, endPath) <> 0 And moveUp <= UBound(tmpArr) Then
retStr = tmpArr(UBound(tmpArr) - moveUp)
End If
GetFolderName = retStr
End Function
所以代码遍历。您发送在上一步中获得的路径,然后您只需将函数调用为,
TextBox1.Text = GetFolderName(fb.SelectedPath)
'Or - However this is redundant as the Optional Parameters are declared as such by default
TextBox1.Text = GetFolderName(fb.SelectedPath, "WINDOW", 2)
以上内容会将您的文本框填充为 "Project"。希望这有帮助!
我有以下代码,但我需要调整。我希望用户从项目中 select 一个特定的文件夹。想象路径 "C:\Project\SomeOtherFolder\WINDOW"。如果 select 编辑了 "WINDOW" 文件夹,下面的代码只会填充文本框。我只是用它来检查用户,但实际上我希望文本框填充 "Project".
Using fb As New FolderBrowserDialog
If fb.ShowDialog = Windows.Forms.DialogResult.OK AndAlso _
(IO.Path.GetFileName(fb.SelectedPath) = "WINDOW") Then
TextBox1.Text = IO.Path.GetFileName(fb.SelectedPath)
Else
Exit Sub
End If
End Using
请问我怎样才能做到这一点?非常感谢!!!
这个 UDF,应该能满足您的需求。我创建了从特定文件夹位置 return 文件夹名称的函数。我已经包含了一些可选参数,因此您可以(如果需要)更改要求。
Public Function GetFolderName(FolderPath As String, _
Optional endPath As String = "WINDOW", _
Optional moveUp As Integer = 2) As String
Dim tmpArr() As String, retStr As String
tmpArr = Split(FolderPath, "\")
If InStr(FolderPath, endPath) <> 0 And moveUp <= UBound(tmpArr) Then
retStr = tmpArr(UBound(tmpArr) - moveUp)
End If
GetFolderName = retStr
End Function
所以代码遍历。您发送在上一步中获得的路径,然后您只需将函数调用为,
TextBox1.Text = GetFolderName(fb.SelectedPath)
'Or - However this is redundant as the Optional Parameters are declared as such by default
TextBox1.Text = GetFolderName(fb.SelectedPath, "WINDOW", 2)
以上内容会将您的文本框填充为 "Project"。希望这有帮助!