将多个工作簿合并为一个工作簿

时间:2019-06-27 18:27:26

标签: excel vba

我在不同的excel中都有区域明智的数据。我想创建一个宏,以将所有Excel文件合并到一个新的工作表中。

我尝试了下面的代码,但是没有用。

    Sub CopyBooks()
    Application.ScreenUpdating = False
    Application.Calculation = xlManual

    Dim destinationWorkbook As Workbook
    Set destinationWorkbook = ThisWorkbook
    Dim lCopyLastRow As Long
    Dim lDestLastRow As Long
    Dim sourceWorkbook As Workbook
    Dim sourceWorksheet As Worksheet
    Const path As String = "C:\Corporate Competition\Excel\merge\"
    Dim file As Variant

    Dim currentSheets As Long
    currentSheets = destinationWorkbook.Sheets.Count

    file = Dir(path & "**.xls**")

    While file <> ""
        Set sourceWorkbook = Workbooks.Open(path & file)
        For Each sourceWorksheet In sourceWorkbook.Worksheets
            sourceWorksheet.Copy
            lCopyLastRow = sourceWorksheet.Cells(sourceWorksheet.Rows.Count, "A").End(xlUp).Row
            lDestLastRow = currentSheets.Cells(ThisWorkbook.Rows.Count, "A").End(xlUp).Offset(1).Row
            sourceWorksheet.Range("A2:D" & lCopyLastRow).Copy _
            ThisWorkbook.Range("A" & lDestLastRow)
            Next
        sourceWorkbook.Close savechanges:=False
        file = Dir
    Wend

    Application.Calculation = xlAutomatic
    Application.ScreenUpdating = True

End Sub

我希望所有文件都一个接一个地追加。另外,用于指示区域名称/ excel文件名的列名称将有很大帮助。

0 个答案:

没有答案