[英]How to combine multiple Excel sheet into one Excel sheet using VBA
I have multiple excel sheets. 我有多张excel表。 Using VBA, I want to combine them into a particular sheet. 使用VBA,我想将它们组合成一个特定的工作表。 For example, combine Sheet1, Sheet4, Sheet5 into one sheet and combine Sheet2, Sheet3, Sheet6 will go into another sheet. 例如,将Sheet1,Sheet4,Sheet5合并到一个工作表中,并将Sheet2,Sheet3,Sheet6合并到另一个工作表中。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.