我可以从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
答案 0 :(得分:5)
这很简单:
Dim filePath, directoryPath As String
filePath = "U:\public\2016\Macro\CD-CW\109 file.xlsx"
directoryPath = Left(filePath, InStrRev(filePath, "\"))
答案 1 :(得分:2)
您可以使用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
答案 2 :(得分:0)
解决方案之一是创建一个简单的函数,用于从该文件夹路径内的文件中提取文件夹路径。我的问题和建议在Related Question。功能代码如下:
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对象,我认为这是不值得的。