目标:将工作表中的数据,根据某一列数据拆分成多个工作表。
操作步骤:
【1】准备数据
【2】打开Excel数据表,另存为【.xlsm】文件,进入【开发工具-->查看代码】(alt+F11) VBA代码界面,粘贴代码后,点击【运行】(F5),等待拆分完毕。代码如下:
Sub NewSheets()
Dim d As Object, sht As Worksheet, arr, brr, r, kr, i&, j&, k&, x&
Dim Rng As Range, Rg As Range, tRow&, tCol&, aCol&, pd&
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set d = CreateObject("scripting.dictionary")
Set Rg = Application.InputBox("请您框选拆分依据列!只能选择单列单元格区域!", Title:="提示", Type:=8)
tCol = Rg.Column
tRow = Val(Application.InputBox("请您输入总表标题行的行数?"))
If tRow = 0 Then MsgBox "您未输入标题行行数,程序退出!": Exit Sub
Set Rng = ActiveSheet.UsedRange
arr = Rng
tCol = tCol - Rng.Column + 1
aCol = UBound(arr, 2)
For i = tRow + 1 To UBound(arr)
If Not d.exists(arr(i, tCol)) Then
d(arr(i, tCol)) = i
Else
d(arr(i, tCol)) = d(arr(i, tCol)) & "," & i
End If
Next
For Each sht In Worksheets
If d.exists(sht.Name) Then sht.Delete
Next
kr = d.keys
For i = 0 To UBound(kr)
If kr(i) <> "" Then
r = Split(d(kr(i)), ",")
ReDim brr(1 To UBound(r) + 1, 1 To aCol)
k = 0
For x = 0 To UBound(r)
k = k + 1
For j = 1 To aCol
brr(k, j) = arr(r(x), j)
Next
Next
With Worksheets.Add(, Sheets(Sheets.Count))
.Name = kr(i)
.[a1].Resize(tRow, aCol) = arr
.[a1].Offset(tRow, 0).Resize(k, aCol) = brr
Rng.Copy
.[a1].PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.[a1].Select
End With
End If
Next
Sheets(1).Activate
Set d = Nothing
Erase arr: Erase brr
MsgBox "数据拆分完成!"
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
【3】填写需要根据哪一列数据进行拆分,然后【确定】。
拆分完成后,结果如下:
欢迎交流学习|如有侵权,敬烦告知。