简体   繁体   English

从文件路径检索文件夹路径

[英]retrieve folder path from file path

I am able to select the file from filedialog function and storing the file path in string. 我可以从filedialog函数中选择文件,并将文件路径存储在字符串中。 but I also want the folder name of the selected path. 但我也想要所选路径的文件夹名称。 Can you please advise as to how to get the folder path from select file. 您能否建议如何从选择文件中获取文件夹路径。

File selected is : 选择的文件是:

U:\public\2016\Macro\CD-CW\109 file.xlsx

I want to show till : 我想展示到:

U:\public\2016\Macro\CD-CW\

My Code 我的密码

Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2010", "*.xlsx"
    .Filters.Add "All Files", "*.*"
    If .Show = True Then
        selfile = .SelectedItems(1) 'replace txtFileName with your textbox
    End If
End With

This is very simple: 这很简单:

Dim filePath, directoryPath As String
filePath = "U:\public\2016\Macro\CD-CW\109 file.xlsx"
directoryPath = Left(filePath, InStrRev(filePath, "\"))

You can use Left with InStrRev functions to remove the last string after the first \\ found from the right side. 您可以将LeftInStrRev函数一起使用,以删除从右侧找到的第一个\\之后的最后一个字符串。

Dim FilePath As String

Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2010", "*.xlsx"
    .Filters.Add "All Files", "*.*"
    If .Show = True Then
        FilePath = Left(.SelectedItems(1), InStrRev(.SelectedItems(1), "\"))
        Debug.Print FilePath 
        selfile = .SelectedItems(1) 'replace txtFileName with your textbox
    End If
End With

One of the solutions is to create a simple function for extracting a folder path from a file that is inside this folder path. 解决方案之一是创建一个简单的函数,用于从该文件夹路径内的文件中提取文件夹路径。 My question and proposal is here Related Question . 我的问题和建议在这里相关问题 Function code is below: 功能代码如下:

Function getFolderPathFromFilePath(filePath As String) As String

    Dim lastPathSeparatorPosition As Long

    lastPathSeparatorPosition = InStrRev(filePath, Application.PathSeparator)

    getFolderPathFromFilePath = Left(filePath, lastPathSeparatorPosition - 1)

End Function

In some solutions for this purpose, I used FSO, but it takes resources, and I think it isn't worthy to create FSO object if you need it only for this simple function. 在一些用于此目的的解决方案中,我使用了FSO,但是它占用了资源,并且我认为如果只需要此简单功能就不需要创建FSO对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM