excel2007拆分工作表的教程
excel2007拆分工作表的教程
Excel中工作表具体该如何拆分呢?接下来是学习啦小编为大家带来的excel2007拆分工作表的教程,供大家参考。
excel2007拆分工作表的教程:
拆分工作表步骤1:首先来看一下原始数据,A列是日期,B列是姓名,后面是名称和数量。需要根据B列的姓名将每个人的数据记录存储为一个单独的工作簿文件。
拆分工作表步骤2:按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 <> "数据源" 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) - 1
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) & "'"
Dim Nowbook As Workbook
Set Nowbook = Workbooks.Add
With Nowbook
With .Sheets(1)
.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
End With
ThisWorkbook.Activate
Sheets(1).Cells.Select
Selection.Copy
Workbooks(Nowbook.Name).Activate
ActiveSheet.Cells.Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Nowbook.SaveAs ThisWorkbook.Path & "\" & k(i)
Nowbook.Close True
Set Nowbook = Nothing
Next i
conn.Close
Set conn = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
拆分工作表步骤5:返回Excel工作表界面,选择【开发工具】-【插入】-【表单控件】-【按钮】。
拆分工作表步骤6:选择完插入按钮后会弹出指定宏的界面,选定刚才插入的“CFGZB”宏,并确定。
拆分工作表步骤7:点击插入的按钮,根据提示选择标题行。
拆分工作表步骤8:根据提示,选择要拆分的列标题,本例是“姓名”。
拆分工作表步骤9:再次点击确定后,宏会自动运行。运行完毕后工作簿所在的同路径下会出现以每个人名命名的独立工作簿。打开每个单个工作簿就可以看到每个人自己的数据记录。