|
楼主 |
发表于 2022-6-5 20:21
|
显示全部楼层
完工:Sub 创建一簿多表数据透视表()
Dim sh As Worksheet, r As Integer, sql As String, cnn As New ADODB.Connection, rst As New ADODB.Recordset, pc As PivotCache, pt As PivotTable
For Each sh In ThisWorkbook.Worksheets
With sh
If .Name <> "合并" Then
r = .Range("a5").End(xlDown).Row
If sql <> "" Then sql = sql & " union all"
sql = sql & " select 姓名, 证件号, 电话, """ & .Name & """ as 表名 from [" & .Name & "$A5:C" & r & "]"
End If
End With
Next
For r = 1 To ThisWorkbook.Connections.Count
ThisWorkbook.Connections(1).Delete
Next
For Each pt In Worksheets(3).PivotTables
pt.TableRange2.Clear
Next
MsgBox sql, , "自动编辑的SQL命令文本:"
cnn.Open "Provider=Microsoft.ace.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName
rst.Open sql, cnn
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal)
Set pc.Recordset = rst
Set pt = pc.CreatePivotTable(Worksheets(3).Range("a1"), TableName:="pt1")
MsgBox "透视表创建完成。"
End Sub |
|