简体   繁体   中英

How to combine multiple Excel sheet into one Excel sheet using VBA

I have multiple excel sheets. Using VBA, I want to combine them into a particular sheet. For example, combine Sheet1, Sheet4, Sheet5 into one sheet and combine Sheet2, Sheet3, Sheet6 will go into another sheet. Basically sheet name needs to be hardcoded while combining.

Modify the below code and try the below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM