如何使用VBA将多个Excel工作表合并为一个Excel工作表

时间:2019-03-18 03:27:09

标签: excel vba

我有多个Excel工作表。使用VBA,我想将它们组合到特定的工作表中。例如,将Sheet1,Sheet4,Sheet5合并为一个工作表,并将Sheet2,Sheet3,Sheet6合并为另一工作表。基本上,工作表名称在合并时需要进行硬编码。

1 个答案:

答案 0 :(得分:0)

修改以下代码,然后尝试以下操作:

Option Explicit

Sub test()

    Dim ws As Worksheet, ws145 As Worksheet, ws236 As Worksheet
    Dim Lastrow As Long

    'Let as assume that data appears in sheet 1
    With ThisWorkbook

        'Set the results sheets
        Set ws145 = .Worksheets("Sheet7")
        Set ws236 = .Worksheets("Sheet8")

        'Loop sheets
        For Each ws In .Worksheets
            'Check sheet name
            If ws.Name = "Sheet1" Or ws.Name = "Sheet4" Or ws.Name = "Sheet5" Then
                Lastrow = ws.cells(ws.Rows.Count, "A").End(xlUp).Row
                Lastrow1 = ws145.cells(ws145.Rows.Count, "A").End(xlUp).Row
                'Copy Column A from row 1 to Lastrow
                ws.Range("A1:A" & Lastrow).Copy ws145.Range("A" & Lastrow1 + 1)
            ElseIf ws.Name = "Sheet2" Or ws.Name = "Sheet3" Or ws.Name = "Sheet6" Then
                Lastrow = ws.cells(ws.Rows.Count, "A").End(xlUp).Row
                Lastrow1 = ws236.cells(ws236.Rows.Count, "A").End(xlUp).Row
                'Copy Column A from row 1 to Lastrow
                ws.Range("A1:A" & Lastrow).Copy ws236.Range("A" & Lastrow1 + 1)
            End If

        Next ws

    End With

End Sub