[英]retrieve folder path from file path
我可以從filedialog函數中選擇文件,並將文件路徑存儲在字符串中。 但我也想要所選路徑的文件夾名稱。 您能否建議如何從選擇文件中獲取文件夾路徑。
選擇的文件是:
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
這很簡單:
Dim filePath, directoryPath As String
filePath = "U:\public\2016\Macro\CD-CW\109 file.xlsx"
directoryPath = Left(filePath, InStrRev(filePath, "\"))
您可以將Left
與InStrRev
函數一起使用,以刪除從右側找到的第一個\\
之后的最后一個字符串。
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
解決方案之一是創建一個簡單的函數,用於從該文件夾路徑內的文件中提取文件夾路徑。 我的問題和建議在這里相關問題 。 功能代碼如下:
Function getFolderPathFromFilePath(filePath As String) As String
Dim lastPathSeparatorPosition As Long
lastPathSeparatorPosition = InStrRev(filePath, Application.PathSeparator)
getFolderPathFromFilePath = Left(filePath, lastPathSeparatorPosition - 1)
End Function
在一些用於此目的的解決方案中,我使用了FSO,但是它占用了資源,並且我認為如果只需要此簡單功能就不需要創建FSO對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.