[英]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.