|
本人在学校工作,经常统计成绩,想把成绩总表拆成分班的工作表放在同一个工作簿中,在网上找了一个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") '建立字典对象变量d
Myr = Worksheets("数据源").UsedRange.Rows.Count 'range 范围 本句为求已经使用范围的行的总数
Arr = Worksheets("数据源").Range(Cells(2, columnNum), Cells(Myr, columnNum)) '选中从等分类列第2行到最后一行赋值给Arr
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
附excel文件在后面
|
|