【问题标题】:VBA - Wait for formulae dependant on PivotTable to update before proceedingVBA - 在继续之前等待依赖数据透视表的公式更新
【发布时间】:2015-07-14 15:13:30
【问题描述】:

根据标题,希望等待依赖数据透视表的公式更新后再继续。

设置(在 Excel 2010 工作簿中):

  1. 数据透视表使用
    • 一个 xlDataField(不变),
    • 几个 xlRowFields(不变)和
    • 一个 xlPageField(用于通过 VBA 更改,以提高数据检索速度)
  2. 使用公式(包括从上述数据透视表派生的 GetPivotData)填充的二维范围(列 x 行)

处理(通过 VBA):

  1. 上面提到的 xlPageField 已更改(期望中的值 上述范围已更新)
  2. 将二维范围“读取”到 Variant 中,以便通过 VBA 进行进一步处理

该过程在步骤 3 和 4 之间失败。范围值在读入 Variant 之前不会更新。可能是数据透视表未更新,依赖于数据透视表的公式未更新,或两者兼而有之。

迄今为止尝试的解决方案(来自各种 StackOverlow 线程或外部网站):

任何指导将不胜感激。

请求的代码(截断)

Dim AllocationRange As Variant
Dim SwitchHistory As PivotTable

Sub Main()
    InitialisePublicVariables

    'For each member
        GetMemberSwitchHistory
        Dim Allocations As New Dictionary: Set Allocations = GetDictionary("Allocations")
    // further processes
    'Next member
End Sub

Private Sub InitialisePublicVariables()
    Set SwitchHistory = Sheets("All Switches (clean)").PivotTables("SwitchHistory")
    AllocationRange = Range("AllocationRange")
End Sub

Private Sub GetMemberSwitchHistory()
    Dim MemberAccountNumber As String: MemberAccountNumber = Range("MemberAccountNumber").Value
    SwitchHistory.PivotFields("Member Account Number").CurrentPage = MemberAccountNumber
    SwitchHistory.RefreshTable
    DoEvents
End Sub

问候 香农

【问题讨论】:

    标签: vba excel pivot-table


    【解决方案1】:

    您能否重构您的代码,以便在更新后可以使用Worksheet 上的PivotTableUpdate 事件对Pivot 进行操作?

    Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    
      Debug.Print "Pivot table updated - do stuff..."
    
    End Sub
    

    您也可以使用PivtoTableChangeSync 事件(这可能更合适,因为它更能识别变化)。

    Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable)
    
      Debug.Print "Pivot table change sync..."
    
    End Sub
    

    有关此活动的更多信息可以在这里找到:- https://msdn.microsoft.com/EN-US/library/office/ff838251.aspx

    【讨论】:

    • xlPageField 作为更广泛循环的一部分更改了大约 2,500 次。我相信 Worksheet_PivotTableChangeSync() 会导致异步代码和更多问题。
    • 你能发布失败的实际代码块吗?您为其设置值的页面字段的数据类型是什么?
    • 失败的代码块将是:Dim SwitchHistory As PivotTable Set SwitchHistory = Sheets("name").PivotTables("SwitchHistory") SwitchHistory.PivotCache.BackgroundQuery = False 导致运行时“1004”。但是,整个(冗长的)代码不会失败,它只是由于刷新/更新失败而返回不正确的结果。如果代码在同一个 xlPageField 上运行两次或更多次,结果是正确的(由于不需要更新数据透视表或相关公式。
    • 这还不够。您需要显示第 3 步和第 4 步中的所有代码,以便我了解实际发生的情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多