excel按條件把表格分割的教程
excel按條件把表格分割的教程
在Excel中有很多情況需要我們?nèi)グ礂l件把表格給分割開來,這個功能比較常用,如果不懂得朋友學習一下也無妨,接下來是學習啦小編為大家?guī)淼膃xcel按條件把表格分割的教程,希望對你有用。
excel按條件把表格分割的教程:
表格分割步驟1:原始數(shù)據(jù)表如下(名稱為:數(shù)據(jù)源),需要根據(jù)B列人員姓名拆分成每個人一個工作表。
表格分割步驟2:點擊【開發(fā)工具】-【Visual Basic】或者Alt+F11的快捷鍵進入VBE編輯界面。
表格分割步驟3:如下圖所示插入一個新的模塊。
表格分割步驟4:如下圖,粘貼下列代碼在模塊中:
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
表格分割步驟5:如下圖所示,插入一個控件按鈕,并指定宏到剛才插入的模塊代碼。
表格分割步驟6:點擊插入的按鈕控件,根據(jù)提示選擇標題行和要拆分的列字段,本例選擇“姓名”字段拆分,當然也可以選擇C列的“名稱”進行拆分,看實際需求。
表格分割步驟7:代碼運行完畢后在工作簿后面會出現(xiàn)很多工作表,每個工作表都是單獨一個人的數(shù)據(jù)。具體如下圖所示:
4.Excel教程