下载链接:https://pan.baidu.com/s/1Tl84iOkex69jmrDHOFlmUA
密码:qp2i
在工作中有时候需要将一张Excel表格拆分成多张,手动操作较为繁琐,于是尝试用VBA自动拆分。
比如下面这张学生成绩表:
学生成绩表想要按学期拆分成第1学期、第2学期的两张表:
第1学期 第2学期要求每张表保留相同的表头。尝试用到的VBA语句为:
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) & "'"
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
简单解释一下:
执行宏CFGZB(拆分工作表),会出现对话框:
选择第一行作为标题行,然后会出现第二个对话框:
选择拆分依据比如你想拆分成第1学期、第2学期两个表格,就选择第一个单元格“学期”。
然后点“确定”,程序就会自动把原excel文件拆分成两个独立的excel文件,保存在同名文件夹下。
生成文件也可以按班级拆分成1班、2班两个表格:
1班 2班某些电脑在运行宏时可能会出现'3706'错误:
3706错误原因可能是没有安装AccessDatabaseEngine.exe,也可能是excel版本不兼容,我一台电脑用office2016出现错误,换了台使用office2010的电脑就运行正常了。
可以参考一下帖子解决问题:
出现了运行时错误‘3706’,未找到提供程序,该程序可能未正确安装
网友评论