excel 在通知Pivot刷新时运行代码,但在进行任何更改之前

bq9c1y66  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(107)

我试图在过滤器/切片器发生变化时运行宏,但要在数据透视表刷新/重新计算之前。
我想出了一个变通的办法,但是如果有一种方法可以在数据透视表更新被请求时触发一个宏,我可以写一个更简单的代码。我知道有一个事件可以在数据透视表完成刷新后使用。
我尝试了以下方法。它们都不起作用,在数据透视表刷新期间也不会触发。

  • PivotTableBeforeAllocateChanges
  • PivotTableBeforeCommitChanges
  • PivotTableBeforeDiscardChanges

我确实在工作表代码中有这些,而不是在模块中。我使用了微软的示例代码。
我想在pivot刷新之前运行的代码:

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    CalcCol = Sheets("References").Range("B1")
    Columns(CalcCol).Delete
End Sub
jei2mxaa

jei2mxaa1#

您可以在Worksheet_Change事件中捕获它,并查看“目标”中是否包含数据透视表更改。如果有更改-您可以撤消它-然后运行代码并重新执行它?
我使用这种方法来捕获对切片器的更改,这样我就可以给人们带来很好的切片器体验,而不是控件或电子表格下拉列表(当我必须单击其中一个时,我会呻吟!)
我的代码如下。

Private Sub Worksheet_Change(ByVal Target As Range)
   'trying to trap pivot table slicer changes
    
    Dim sc As SlicerCache
    Dim si As SlicerItem
    Dim boolFoundFirstSelect As Boolean
    Dim intCountSelected As Integer, intCountNOTSelected As Integer
    
    On Error Resume Next
    Set sc = Target.PivotTable.Slicers(1).SlicerCache
    If Err <> 0 Then
        On Error Resume Next
        Exit Sub 'leave if they are changing anything else
    End If
    
    On Error Resume Next
    'Debug.Assert 1 = 2 'Turn this on & explore the Target object to find something you can test
    For Each si In sc.SlicerItems
        If si.Selected = True Then
            intCountSelected = intCountSelected + 1
            strSelectedOption = si.Name 'this will get the LAST name ... but - in the case where there is just ONE selected, this will be useful
        Else
            intCountNOTSelected = intCountNOTSelected + 1
        End If
    Next
    'then do something ...
End Sub

相关问题