首页 > 解决方案 > Excel - 在 Power Query 自动刷新数据透视表源时刷新数据透视表数据

问题描述

我有一个数据库,它每 15 分钟从外部源自动刷新和更新表。我尝试了以下代码,每次编辑/添加/删除源数据时都会更新数据透视表:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Worksheets("PIVOT TABLE WORKSHEET").PivotTables("PIVOT TABLE NAME").RefreshTable
End Sub

当我手动编辑源数据时,数据透视表会相应刷新。但是,当源数据自动更新时,数据透视表保持不变。有没有办法让数据透视表与数据库一起刷新而不需要用户输入?

标签: excelvbapivot-table

解决方案


如果您使用event而不是event ,您将获得更好的结果Worksheet_ChangeWorksheet_SelectionChange这样程序会在数据更改时运行,而不是在您使用鼠标或键盘选择单元格时运行。

Worksheet_Change Worksheet_SelectionChange事件

  • Worksheet_SelectionChange当工作表上的选择更改时触发。
    例如,当用户单击单元格或按下箭头键时。

  • Worksheet_Change当用户外部链接更改工作表上的单元格时触发。

注意: Worksheet_Change does **not** occur when cells change during a re-calculation; use the Calculate` 事件以捕获工作表重新计算。)

根据数据在工作表中的布局方式,您可能希望通过检查更改了哪些单元格来限制此过程的执行,通过将事件过程的Target参数与特定单元格或单元格范围,使用Intersect函数。

注意:当心无穷大!

当使用代码更改事件过程“监视”的区域内的单元格时Worksheet_Change,您可能会进入无限循环,因为更改会再次触发事件,从而再次更改单元格,等等。


(点击图片放大。)

有几种方法可以避免这种情况。最常见的做法是在Change事件执行它需要执行的操作时暂时禁用Application.EnableEvents属性的事件。(不要忘记在程序结束时重新启用事件......请参见下面的示例。)


例子:

这是一个使用所有这些要点的未经测试的示例:

Private Sub Worksheet_Change(ByVal Target As Range)
    Const cellsToWatch = "A1:D4"
    With Worksheets("PIVOT TABLE WORKSHEET")
        'exit the procedure if at least part of the changed cells were not within `A1:D4`
        If Application.Intersect(.Range(cellsToWatch), Target) Is Nothing Then
            'the change wasn't within `cellsToWatch`
            Exit Sub
        End If
        Application.EnableEvents = False 'disable execution of this or other events

        '----------Run your code here:--------------
        .Calculate
        .PivotTables("PIVOT TABLE NAME").RefreshTable
        '-------------------------------------------

        Application.EnableEvents = True  're-enable events
    End With
End Sub

更多信息:


推荐阅读