excel拆分工作表教程
在excel中,经常因为数据的关系需要根据条件拆分工作表,而拆分工作表却是一件比较复杂的事,接下来请欣赏读文网小编给大家网络收集整理的excel拆分工作表教程。
原始数据表如下(名称为:数据源),需要根据B列人员姓名拆分成每个人一个工作表。
excel拆分工作表教程1:点击【开发工具】-【Visual Basic】或者Alt+F11的快捷键进入VBE编辑界面。
excel拆分工作表教程2:如下图所示插入一个新的模块。
excel拆分工作表教程3:如下图,粘贴下列代码在模块中:
SubCFGZB()
Dim myRange As Variant
Dim myArray
Dim titleRange As Range
Dim title As String
Dim columnNum As Integer
myRange = Application.InputBox(prompt:="请选择标题行:", Type:=8)
myArray = WorksheetFunction.Transpose(myRange)
Set titleRange = Application.InputBox(prompt:="请选择拆分的表头,必须是第一行,且为一个单元格,如:“姓名”", Type:=8)
title = titleRange.Value
columnNum = titleRange.Column
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim i&, Myr&, Arr, num&
Dim d, k
For i = Sheets.Count To 1 Step -1
If Sheets(i).Name <> "数据源" Then
Sheets(i).Delete
End If
Next i
Set d = CreateObject("Scripting.Dictionary")
Myr = Worksheets("数据源").UsedRange.Rows.Count
Arr = Worksheets("数据源").Range(Cells(2, columnNum), Cells(Myr, columnNum))
For i = 1 To UBound(Arr)
d(Arr(i, 1)) = ""
Next
k = d.keys
For i = 0 To UBound(k)
Set conn = CreateObject("adodb.connection")
conn.Open "provider=microsoft.jet.oledb.4.0;extended properties=excel 8.0;data source=" & ThisWorkbook.FullName
Sql = "select * from [数据源$] where " & title & " = '" & k(i) & "'"
Worksheets.Add after:=Sheets(Sheets.Count)
With ActiveSheet
.Name = k(i)
For num = 1 To UBound(myArray)
.Cells(1, num) = myArray(num, 1)
Next num
.Range("A2").CopyFromRecordset conn.Execute(Sql)
End With
Sheets(1).Select
Sheets(1).Cells.Select
Selection.Copy
Worksheets(Sheets.Count).Activate
ActiveSheet.Cells.Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Next i
conn.Close
Set conn = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
excel拆分工作表教程4:如下图所示,插入一个控件按钮,并指定宏到刚才插入的模块代码。
excel拆分工作表教程5:点击插入的按钮控件,根据提示选择标题行和要拆分的列字段,本例选择“姓名”字段拆分,当然也可以选择C列的“名称”进行拆分,看实际需求。
excel拆分工作表教程6:代码运行完毕后在工作簿后面会出现很多工作表,每个工作表都是单独一个人的数据。具体如下图所示: