VBA - 等待取决于数据透视表的公式更新,然后再继续

VBA - Wait for formulae dependant on PivotTable to update before proceeding

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

设置(在Excel 2010工作簿):

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

正在处理(通过 VBA):

  1. 上面提到的xlPageField被改变了(期望值在 上述范围已更新)
  2. Two-dimensional 将范围“读取”到变体中,以便通过 VBA
  3. 进行进一步处理

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

迄今为止尝试的解决方案(来自各种 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

问候 香农

您能否重构您的代码,以便您可以在 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