2017-03-07 206 views
0

我能够从文件对话框功能中选择文件并将文件路径存储在字符串中。但我也想要所选路径的文件夹名称。你可以请告知如何从选择文件中获取文件夹路径。选择从文件路径检索文件夹路径

文件是:

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

我想说明,直到:

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

我的代码

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 
+6

的复制(http://stackoverflow.com/questions/42462625/how-to-remove-the-last-element-from-a- [如何从VBA的路径删除最后一个元件] path-in-vba) –

+0

此问题已经有答案[这里](http://stackoverflow.com/a/42462687/4926357) –

+0

[使用'Scripting.FileSystemObject'](http://stackoverflow.com/文档/ VBA/990 /脚本,FileSystemObject的/ 11587 /检索,只有最路径从-A-文件路径)。它比解析文本更不容易出错。 – Comintern

回答

3

这是非常简单的:

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

不,这不只是发生了,你怎么能快速输入:) –

1

您可以使用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 
+0

可能“勇敢”downvoter解释为什么 –

+1

这不是我。我在评论部分做了我的评论,但是我并没有对downvoting做出很好的回答:) –

+0

@ A.S.H我不这么认为,只是好奇他是谁,还有更多为什么? –