|
楼主 |
发表于 2022-6-4 15:37
|
显示全部楼层
加入连接语句也没用。
Sub 按钮1_Click()
Dim sh As Worksheet, r As Integer, sql As String, pc As PivotCache, pt As PivotTable
For r = 1 To ThisWorkbook.Connections.Count
ThisWorkbook.Connections(1).Delete
Next
For Each pt In Worksheets(3).PivotTables
pt.TableRange2.Clear
Next
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 [" & ThisWorkbook.FullName & "].[" & .Name & "$A5:C" & r & "]"
End If
End With
Next
MsgBox sql, , "自动编辑的SQL命令文本:"
' Debug.Print sql
ThisWorkbook.Connections.AddFromFile ThisWorkbook.FullName
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:=ThisWorkbook.Connections(1).Name, Version:=xlPivotTableVersion12)
With pc
.Connection = Array("OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES"";")
.CommandType = xlCmdSql
.CommandText = sql
.RefreshOnFileOpen = True
End With
Set pt = pc.CreatePivotTable(tabledestination:="合并!R1C1", tablename:="pt1")
Set sh = Nothing
Set pt = Nothing
Set pc = Nothing
MsgBox "透视表创建完毕。"
End Sub |
|