使用VBA将文件夹导入Excel(FileDialogFolderPicker)

use*_*563 2 excel vba

我正在使用下一个代码来从某个路径中选择一个文件夹并导入其中的所有文件:

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
Run Code Online (Sandbox Code Playgroud)

当"文件夹选择器"窗口打开时,它将从桌面开始.有没有办法让它在打开时进入特定的路径?或打开excel文件本身所在的位置?

tig*_*tar 7

您将更新InitialFileName属性,并且可以将其设置为使用ActiveWorkbook.Path您需要确保包含结尾斜杠,否则它将仅显示上一个文件夹而不是您想要的文件夹.此外,没有理由循环遍历.SelectedItems集合,因为FolderPicker FileDialog不支持多重选择.

总之,我认为这是您正在寻找的代码:

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
Run Code Online (Sandbox Code Playgroud)