在Excel中,你可以使用VBA(Visual Basic for Applications)来创建一个汇总表,将多个工作表中的数据汇总到一个单独的工作表中。以下是创建汇总表的步骤和示例代码:
步骤1:打开VBA编辑器
1. 按下 `Alt + F11` 打开VBA编辑器。
步骤2:插入模块
1. 在左侧的“工程”窗口中,右键单击你的工作簿名称,选择“插入” -> “模块”。
步骤3:编写VBA代码
示例1:生成汇总表
```vba
Sub 生成汇总表()
Dim dic As Object
Dim key As Variant
Dim arr As Variant
Dim lastRow As Long
' 获取数据区域
lastRow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
arr = Sheets("Sheet1").Range("A2:C" & lastRow).Value
' 统计数据
Set dic = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr, 1)
key = arr(i, 2) ' 产品作为键
If dic.exists(key) Then
dic(key) = dic(key) + arr(i, 3) ' 累加销售额
Else
dic.Add key, arr(i, 3)
End If
Next i
' 输出汇总表
Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(dic.Count, 3).Value = dic.Items
End Sub
```
示例2:汇总所有工作表数据
```vba
Sub 汇总所有工作表数据()
Dim ws As Worksheet
Dim targetWs As Worksheet
Dim i As Long
Dim lastRow As Long
Set targetWs = ThisWorkbook.Sheets("汇总表") ' 数据汇总到“汇总表”,如果没有就新建一个
On Error Resume Next
Set targetWs = Nothing
On Error GoTo 0
If targetWs Is Nothing Then
Set targetWs = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
targetWs.Name = "汇总表"
End If
i = 1 ' 从第一行开始写入数据
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "汇总表" Then ' 避免汇总表自身的数据
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
If lastRow > 1 Then ' 至少有两行数据(包含标题行)
ws.Range("A2:E" & lastRow).Copy Destination:=targetWs.Cells(targetWs.Range("A" & targetWs.Rows.Count).End(xlUp).Row + 1, 1)
End If
End If
Next ws
End Sub
```
示例3:多表合并对账