【问题标题】:Excel VBA/button to refresh two or more pivots simultaneouslyExcel VBA/按钮同时刷新两个或多个枢轴
【发布时间】:2017-08-04 12:38:48
【问题描述】:

在另一篇文章中,我获得了以下 VBA 代码,用于附加到“刷新”按钮以刷新 Pivot 数据:

Option Explicit

Sub Button5_Click()

Dim PvtTbl                  As PivotTable
Dim PvtCache                As PivotCache
Dim PvtDataRng              As Range

' Set/Update Pivot Data Range
Set PvtDataRng = Worksheets("PivotDataSheet").Range("A1:E100") ' <-- just an example

' Create/Update Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)

' Set the Pivot Table (already created, otherwise need to create it)
Set PvtTbl = Worksheets("DD").PivotTables("test")

' refresh the Pivot Table with the latest Pivot Cache
With PvtTbl
    .ChangePivotCache PvtCache
    .RefreshTable
End With

End Sub

如何修改此代码以同时刷新同一工作表中的第二个数据透视?让我们将此第二个枢轴称为“test2”,它也在 DD 工作表中。

谢谢, 凯夫博

【问题讨论】:

  • 只需使用其他数据透视表名称重复您获得的代码的步骤...
  • 第二个名为“test2”的数据透视表是否与第一个数据透视表具有相同的数据源?
  • 两个数据透视表是否基于相同的数据源?
  • 是的,他们使用相同的数据源。不会添加此代码的副本会覆盖 Set PvtTbl =? 的定义

标签: vba excel


【解决方案1】:

如果您在“DD”工作表中只有这 2 个 PivotTable,并且您想根据相同的 PivotCache 更新这 2 个,则替换以下 For 循环:

With PvtTbl
    .ChangePivotCache PvtCache
    .RefreshTable
End With

使用以下For 循环:

' refresh all Pivot Tables in "DD" worksheet
For Each PvtTbl In Worksheets("DD").PivotTables
    With PvtTbl
        .ChangePivotCache PvtCache
        .RefreshTable
    End With
Next PvtTbl

编辑 1Set PivotCacheFor 循环内,并在最后清除它。使用下面的循环,并从之前的位置删除 Set PvtCache 行。

' refresh all Pivot Tables in "DD" worksheet
For Each PvtTbl In Worksheets("DD").PivotTables
    ' Create/Update Pivot Cache
    Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)

    With PvtTbl
        .ChangePivotCache PvtCache
        .RefreshTable
    End With

    Set PvtCache = Nothing ' <-- clear the Pivot Cache
Next PvtTbl

【讨论】:

  • 差不多了...收到运行时错误 5:“Invalid Procure call or argument”在线:'.ChangePivotCache PvtCache'
  • @Kevbo 在第一个 PivotTable 上失败了吗?还是第二个?
  • 看起来像第二个,因为第一个刷新了。
【解决方案2】:

我自己没有对此进行测试,但您可以尝试告诉我它是否有效。看起来它可能对你有用

Function refreshPTcontent()

Dim ws As Worksheet
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem

On Error Resume Next
    For Each ws In ActiveWorkbook.Worksheets
       For Each pt In ws.PivotTables
         pt.RefreshTable
       Next pt
    Next ws

End Function

【讨论】:

猜你喜欢
  • 2018-11-27
  • 2019-07-13
  • 1970-01-01
  • 2017-09-09
  • 2016-03-06
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多