把一个excel拆分成多个工作表
工作中经常会遇到把一个工作表分成若干个表格的时候,以其中的某个条件命名表
格名统计分类建立表格,如果数据很多的话工作量也是很大的,有没有准确快捷的
办法呢,和小编一起操作吧。
操作方法
- 01
打开表格命名为数据源,点击【开发工具】-点击Visual Basic
- 02
在Visual Basic窗口中点击左边的Sheet(数据源),然后点击 插入-【模块】
- 03
在弹出的模块窗口中复制如下代码: 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 <> "数据源" 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 Application.CutCopyMode = False Next i conn.Close Set conn = Nothing Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub
- 04
返回excel表格中,在【开发工具】中-【插入】-点击按钮
- 05
选择宏CFGZB,然后确认
- 06
电钮按钮,在弹出的对话框中选择标题行,然后确定
- 07
选择要拆分的表头,也就是拆分的表格以哪个字段命名,选择标题,点击确定。
- 08
等待完成就可以了,查看效果