表格中有多个工作表,现在需要按照第 1~6 行的标题,对工作表中的数据进行合并汇总。 请你写一个 VBA 代码完成数据的合并,要求如下: 1. 1~6 行的标题,不要重复的合并标题 2. 合并时,第 1 列写入工作表的名称,方便了解数据来源
Sub MergeSheetsWithSource()
Dim wsSummary As Worksheet
Dim ws As Worksheet
Dim lastRow As Long
Dim summaryRow As Long
Dim headerCopied As Boolean
Dim i As Integer
' 创建汇总表
Set wsSummary = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsSummary.Name = "汇总数据"
' 初始化标志
headerCopied = False
summaryRow = 1
Application.ScreenUpdating = False
' 遍历所有工作表
For Each ws In ThisWorkbook.Sheets
If ws.Name <> wsSummary.Name Then ' 跳过汇总表
' 处理标题行(1-6 行)
If Not headerCopied Then
' 添加数据来源列
ws.Rows("1:6").Copy
wsSummary.Cells(summaryRow, 1).PasteSpecial xlPasteAll
wsSummary.Cells(1, 1).Value = "数据来源"
' 调整列位置
wsSummary.Columns(1).Insert Shift:=xlToRight
summaryRow = 7 ' 跳过标题行
headerCopied = True
End If
' 处理数据行(从第 7 行开始)
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
If lastRow >= 7 Then
Dim dataRange As Range
Set dataRange = ws.Range("A7:Y" & lastRow)
' 复制数据并添加来源
dataRange.Copy
wsSummary.Cells(summaryRow, 2).PasteSpecial xlPasteValues
' 添加工作表名称到第一列
wsSummary.Range(wsSummary.Cells(summaryRow, 1), _
wsSummary.Cells(summaryRow + dataRange.Rows.Count - 1, 1)) = ws.Name
summaryRow = summaryRow + dataRange.Rows.Count
End If
End If
Next ws
' 格式整理
With wsSummary
.Columns(1).ColumnWidth = 20
.Columns(2).ColumnWidth = 15
.Rows("1:6").Font.Bold = True
.Cells(1, 1).EntireRow.Insert ' 添加标题分隔行
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
MsgBox "数据合并完成!共合并 " & summaryRow - 7 & " 行数据", vbInformation
End Sub