VBA查找工作簿保存在其中的文件夹

时间:2018-11-23 13:30:47

标签: excel vba

我有一些代码可以挑选出文件夹中的所有xlsx文件,并将它们放入一个工作簿中。我想知道是否可以让VBA查找保存主工作簿的文件夹,或者VBA是否可以询问我要选择哪个文件夹。

Sub GetSheets()

    Path = "S:\xxxxx\"
    Filename = Dir(Path & "*.xlsx")
    Do While Filename <> ""
        Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
            For Each Sheet In ActiveWorkbook.Sheets
            Sheet.Copy After:=ThisWorkbook.Sheets(1)
            Next Sheet
        Workbooks(Filename).Close
        Filename = Dir()
    Loop
    Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:1)

Path = ThisWorkbook.Path

应该可以解决问题。

答案 1 :(得分:1)

您可以参考以下内容:

        Sub openfldr()

        Dim fldr As FileDialog
        Dim sItem As String
        Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
        With fldr
            .Title = "Select a Folder"
            .AllowMultiSelect = False
            .InitialFileName = Application.DefaultFilePath
            If .Show <> -1 Then GoTo NextCode
            sItem = .SelectedItems(1)
        End With
NextCode:
        GetFolder = sItem
        Set fldr = Nothing
    End Sub