下面介绍一下excel将一个工作表根据条件拆分成多个工作簿的方法。
方法
原始数据如下图
按Alt+F11进入VBE界面。
点击“插入”,选择“模块”
双击模块
在空白窗口粘贴以下代码:
Sub CFGZB()
Dim myRange As Variant
Dim myArray
Dim titleRange As Range
Dim title As String
Dim columnNum As Integer
myRange = Application.Inpu活胞会工永适器毫另排都tBox(prompt:="请选择标题行:", Type:=8)
myArray = WorksheetFunction.Transpose(myRange)
Set titleRange = Application.InputBox(prompt:="请选择拆分的表头,必须是第一行,且为一个单元格,如:“姓名”", Type:=8)
title = titleRange.Value
columnNum = titleRange.Column
Appli局沙消皇者每cation.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("数据源").UsedRang越州激烟相八e.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) & "'"
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
ThisW听钱致器井印门宗种鲜万orkbook.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.Scre训养鲜座之enUpdating = True
End Sub
返回Excel工作表界面,点击“开发工具”,选择“插入”,点击“按钮”
指定宏。
点击插入的按钮,根据提示选择标题行。
根据提示,选择要拆分的列标题,以“姓名”为例。
再次点击确定后,宏会自动运行。运行完毕后工作簿所在的同路径下会出现以每个人名命名的独立工作簿。打开每个单个工作簿就可以看到每个人自己的数据记录。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 951076433@qq.com 举报,一经查实,本站将立刻删除。如若转载,请注明出处:https://www.xiaomafuwu.com/210033.html