使用 VBA 将文件夹导入 Excel (FileDialogFolderPicker)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18136528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing folder to Excel (FileDialogFolderPicker) using VBA
提问by user1040563
I'm using the next code in order to select a folder from a certain path and import all the files inside it:
我正在使用下一个代码,以便从某个路径中选择一个文件夹并导入其中的所有文件:
Function GetFolder()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
fd.Title = "Select Excel Workbook(s) Folder"
Dim vrtSelectedItem As Variant
With fd
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
GetFolder = vrtSelectedItem
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Function
When the Folder Picker window opens it start on the desktop. Is there a way to make it go to a specific path upon opening? or open where the excel file itself is located?
当文件夹选择器窗口打开时,它会在桌面上启动。有没有办法让它在打开时进入特定的路径?或打开excel文件本身所在的位置?
回答by tigeravatar
You would update the InitialFileName property, and you could set it to use the ActiveWorkbook.Path You'll need to make sure that you include the ending slash, or it will only display the previous folder instead of the folder you want. Also, there is no reason to loop through the .SelectedItems collection because the FolderPicker FileDialog doesn't support mutliple selections.
您将更新 InitialFileName 属性,并且可以将其设置为使用 ActiveWorkbook.Path 您需要确保包含结尾斜杠,否则它只会显示前一个文件夹而不是您想要的文件夹。此外,没有理由遍历 .SelectedItems 集合,因为 FolderPicker FileDialog 不支持多重选择。
In summary, I think this is the code you're looking for:
总之,我认为这是您正在寻找的代码:
Function GetFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = ActiveWorkbook.Path & Application.PathSeparator
.Title = "Select Excel Workbook(s) Folder"
If .Show = True Then
GetFolder = .SelectedItems(1)
Else
GetFolder = False
End If
End With
End Function
回答by mr.Reband
add a line like this before .Show
:
在之前添加这样的一行.Show
:
fd.InitialFileName = "c:\whateverInitialDirectory"