将多个excel工作簿合并到一个主工作簿中

时间:2018-06-04 02:44:30

标签: excel excel-vba vba

正如上文标题中所述。我一直在寻找方法。 我尝试过使用VB脚本将excel工作簿合并到一个excel工作簿中的方法。但是,当我正在编写脚本时,没有迹象表明将所有工作簿编译到主工作簿中。

这是我完成的VB脚本:

Sub GetSheets()
Path = "C:\Users\..."
Filename = Dir(Path & ".xlsx") 
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=This.Workbook.Sheets(1)
Next Sheet 
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub

1 个答案:

答案 0 :(得分:0)

当您打开工作簿时,它将成为活动工作簿。

Sub GetSheets()

    Path = "C:\Users\..."
    Filename = Dir(Path & "*.xlsx")
    Dim Wb As Workbook
    Dim Wb0 As Workbook: Set Wb0 = ActiveWorkbook
    Dim Sh As Worksheet

    Do While Filename <> ""
        Set Wb = Workbooks.Open(Path & Filename)

        For Each Sh In Wb.Sheets
            Sh.Copy After:=Wb0.Sheets(Wb0.Sheets.Count)
        Next Sh

        Wb.Saved = True
        Wb.Close
        Filename = Dir()
    Loop

End Sub