excel將一個工作表根據條件拆分成多個sheet工作表
阿新 • • 發佈:2018-11-10
本例介紹在excel中如何將一個工作表根據條件拆分成多個工作表。
注意:很多朋友反映sheets(i).delete這句程式碼出錯,要注意下面第一個步驟,要拆分的資料工作表名稱為“資料來源”,
而不是你新建工作簿時的sheet1這種。手動改成“資料來源”即可。或者是把程式碼中得"資料來源"改為你得源工作表“Sheet1”也行
先展示最後效果:
開始步驟例子:
- 程式碼如下
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 <> "Sheet1" Then Sheets(i).Delete End If Next i Set d = CreateObject("Scripting.Dictionary") Myr = Worksheets("Sheet1").UsedRange.Rows.Count Arr = Worksheets("Sheet1").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 [Sheet1$] 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
6.
7.
8.
9.
10
11.
12注意:
1)原始資料表要從第一行開始有資料,並且不能有合併單元格;
2)開啟工作簿時需要開啟巨集,否則將無法執行程式碼。