|
excel操作透视表,比较麻烦,主要是代码通用性不强:
功能给你写出来了, 好好研究吧,基础差点的都不一定能改的了;
效果演示:
核心代码:其它代码见附件
- Sub 一键透视()
- Dim Ado As Object, conStr As String, SQL As String
- Set Ado = CreateObject("ADODB.Connection")
- If Application.Version >= 11 Then
- conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES"";"
- Else
- conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 8.0;HDR=YES"";"
- End If
- Ado.Open conStr
- SQL = "SELECT 类别,Total,Taken FROM [Sheet2$E1:G7]"
- If Ado.State = 1 Then Debug.Print "测试链接成功!" Else Debug.Print "测试链接失败!": Exit Sub
- 'Exit Sub
- With GetWorksheet(ThisWorkbook, "Sheet2-结果")
- .Visible = xlSheetVisible
- .Cells.Clear
- .Activate
- Set objPivotCache = .Parent.PivotCaches.Create(SourceType:=xlExternal)
- '设定数据透视表缓存对象的记录集为指定的Recordset对象
- Set objPivotCache.Recordset = Ado.Execute(SQL)
- '创建透视表
- With objPivotCache.CreatePivotTable(TableDestination:=.Range("A1"), TableName:=.Name)
- '设置手动更新
- .ManualUpdate = False
- '隐藏值行
- .ShowValuesRow = False
- '隐藏折叠按钮
- .ShowDrillIndicators = False
- '设置行标签
- .PivotFields("类别").Orientation = xlRowField
- .PivotFields("类别").Position = 1
- '添加度量值
- .AddDataField .PivotFields("Total"), "Total合计", xlSum
- .AddDataField .PivotFields("Taken"), "Taken合计", xlSum
- End With
- .UsedRange.EntireColumn.AutoFit
- End With
- Ado.Close
- Set Ado = Nothing
- End Sub
复制代码 附件在这里:
回复:工作簿1-20230506.zip
(24.85 KB, 下载次数: 5)
|
|