VBA - 从路径中提取特定文件夹名称

时间:2015-03-03 10:45:24

标签: vba folderbrowserdialog

我有以下代码,但我需要调整。我希望用户从项目中选择特定文件夹。想象一下路径“C:\ Project \ SomeOtherFolder \ WINDOW”。如果已选择“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

我该如何做到这一点?非常感谢!!!

1 个答案:

答案 0 :(得分:1)

这个UDF应该能满足你的需求。我创建了从特定文件夹位置返回文件夹名称的函数。我已经包含了一些可选参数,因此您可以(如果需要)更改要求。

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)

上面会将您的文本框填充为“项目”。希望这有帮助!