欢迎光临
我们一直在努力

【Excel】怎样将一个工作表根据条件拆分成多个工作表

本文将介绍在excel中如何将一个工作表根据条件拆分成多个工作表。

操作步骤:

1、原始数据表如下(名称为:总表),需要根据A列序号拆分成每个品种一个工作表。

2、按下Alt+F11快捷键进入VBE编辑界面。

3、插入一个新的模块。

4、在“模块1”中粘贴代码:(注意:代码中的“总表”就是excel中要分割的工作表的名字,可根据实际修改,

代码中的引号都是英文半角,若提示语法不正确,请手动修改下

Sub 拆分总表()
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
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、返回excel,按下 ALT + F8

6、点击执行。

7、等待执行完毕。

赞(0) 打赏
未经允许不得转载:天天微站 » 【Excel】怎样将一个工作表根据条件拆分成多个工作表

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏