如何使用Excel上的VBA将单个选项卡从工作簿复制到主工作簿

时间:2016-01-15 16:39:12

标签: excel vba excel-vba

我正在尝试从指定文件夹中的多个工作簿中将一个选项卡拉入主工作簿。到目前为止,这就是我所拥有的:

Sub GetSheets()
Path = "D:\APQP\APQP\Open Projects\"
Filename = Dir(Path & "*.xlsx")
  Do While Filename <> ""
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
     For Each Sheet In ActiveWorkbook.Sheets
     Sheets("5-Phase").Select
     Sheets("5-Phase").Copy Before:=ThisWorkbook.Sheets(1)
  Next
     Workbooks(Filename).Close
     Filename = Dir()
  Loop
End Sub

现在,当我运行它时,它会使用文件夹中第一个wookbook中的50个选项卡填充主工作簿,而不是复制选项卡并转到下一个工作簿并处理该工作簿中的选项卡。任何帮助都会很棒。

1 个答案:

答案 0 :(得分:2)

您的代码存在两个主要问题。 For循环是不必要的,您不使用打开的工作簿。这样的事情对你有用:

Sub GetSheets()

    Dim wb As Workbook
    Dim sPath As String
    Dim sFileName As String

    Set wb = ThisWorkbook
    sPath = "D:\APQP\APQP\Open Projects\"
    sFileName = Dir(sPath & "*.xlsx")

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    On Error Resume Next
    Do While Len(sFileName) > 0
        With Workbooks.Open(sPath & sFileName, ReadOnly:=True)
            .Sheets("5-Phase").Copy Before:=wb.Sheets(1)
            .Close False
        End With
        sFileName = Dir()
    Loop
    On Error GoTo 0

    Application.ScreenUpdating = True
    Application.EnableEvents = True

End Sub