2017-03-07 163 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我不這麼認爲,只是好奇他是誰,還有更多爲什麼? –