Excel 宏:按部门和月份拆分汇总表数据到多个工作表
使用 Excel 的宏功能可以轻松实现将汇总表数据按部门和月份拆分到多个工作表。
以下是实现此功能的 VBA 代码示例:
Sub SplitDataByDepartmentAndMonth()
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long, i As Long, j As Long
Dim departments As Object, department As Variant
Dim months As Object, month As Variant
Dim newWs As Worksheet
' 获取当前工作表
Set ws = ActiveSheet
' 获取最后一行和最后一列的行号和列号
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' 创建部门和月份的集合
Set departments = CreateObject("Scripting.Dictionary")
Set months = CreateObject("Scripting.Dictionary")
' 遍历原始数据,将部门和月份添加到集合中
For i = 2 To lastRow
department = ws.Cells(i, 2).Value
month = Format(ws.Cells(i, 1).Value, "yyyy-mm")
If Not departments.Exists(department) Then
departments.Add department, department
End If
If Not months.Exists(month) Then
months.Add month, month
End If
Next i
' 遍历部门和月份的组合,创建新的 SHEET 并拆分数据
For Each department In departments
For Each month In months
' 创建新的 SHEET
Set newWs = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
newWs.Name = department & " - " & month
' 复制表头
ws.Rows(1).Copy newWs.Rows(1)
' 拆分数据
j = 2 ' 记录新 SHEET 的行号
For i = 2 To lastRow
If ws.Cells(i, 2).Value = department And Format(ws.Cells(i, 1).Value, "yyyy-mm") = month Then
ws.Rows(i).Copy newWs.Rows(j)
j = j + 1
End If
Next i
Next month
Next department
End Sub
使用方法:
- 打开 Excel 文件,并按下
ALT + F11打开 VBA 编辑器。 - 在 VBA 编辑器中,插入一个新的模块(右键点击项目资源管理器中的文件夹,选择“插入”->“模块”)。
- 将上述代码复制粘贴到新插入的模块中。
- 关闭 VBA 编辑器。
- 返回 Excel 文件,在要拆分的汇总表中,按下
ALT + F8来运行宏。 - 在弹出的对话框中选择“SplitDataByDepartmentAndMonth”宏,并点击“运行”按钮。
完成以上步骤后,你将会看到按部门按月拆分成多个工作表的结果。每个工作表的名称将会由部门名称和月份组成。
原文地址: http://www.cveoy.top/t/topic/qzGU 著作权归作者所有。请勿转载和采集!