excel拆分工作表教程
excel拆分工作表教程
在Excel中,經(jīng)常因為數(shù)據(jù)的關(guān)系需要根據(jù)條件拆分工作表,而拆分工作表卻是一件比較復雜的事,接下來請欣賞學習啦小編給大家網(wǎng)絡(luò)收集整理的excel拆分工作表教程。
原始數(shù)據(jù)表如下(名稱為:數(shù)據(jù)源),需要根據(jù)B列人員姓名拆分成每個人一個工作表。
excel拆分工作表教程1:點擊【開發(fā)工具】-【Visual Basic】或者Alt+F11的快捷鍵進入VBE編輯界面。
excel拆分工作表教程2:如下圖所示插入一個新的模塊。
excel拆分工作表教程3:如下圖,粘貼下列代碼在模塊中:
Sub CFGZB()
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 <> "數(shù)據(jù)源" Then
Sheets(i).Delete
End If
Next i
Set d = CreateObject("Scripting.Dictionary")
Myr = Worksheets("數(shù)據(jù)源").UsedRange.Rows.Count
Arr = Worksheets("數(shù)據(jù)源").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 [數(shù)據(jù)源$] 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:點擊插入的按鈕控件,根據(jù)提示選擇標題行和要拆分的列字段,本例選擇“姓名”字段拆分,當然也可以選擇C列的“名稱”進行拆分,看實際需求。
excel拆分工作表教程6:代碼運行完畢后在工作簿后面會出現(xiàn)很多工作表,每個工作表都是單獨一個人的數(shù)據(jù)。具體如下圖所示: