excel - Excel - 在 Power Query 自动刷新数据透视表源时刷新数据透视表数据
问题描述
我有一个数据库,它每 15 分钟从外部源自动刷新和更新表。我尝试了以下代码,每次编辑/添加/删除源数据时都会更新数据透视表:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Worksheets("PIVOT TABLE WORKSHEET").PivotTables("PIVOT TABLE NAME").RefreshTable
End Sub
当我手动编辑源数据时,数据透视表会相应刷新。但是,当源数据自动更新时,数据透视表保持不变。有没有办法让数据透视表与数据库一起刷新而不需要用户输入?
解决方案
如果您使用event而不是event ,您将获得更好的结果Worksheet_Change
,Worksheet_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
更多信息:
推荐阅读
- r - 在 ggplot 图中按类型重新排序 sf 多边形
- python - 如何分配 Numpy 数组的特定部分?
- c# - Microsoft.ml 找不到 csv 文件,即使它在我的文件目录中
- button - 未解决的参考按钮
- angular - ngIf 带有 as as 语法和 && 运算符
- java - 如何从末尾获取字符串的每个字符的索引
- scikit-learn - 在训练和测试数据上拟合 CountVectorizer,以免遗漏任何单词
- javascript - 未捕获的类型错误:无法在 HTMLButtonElement.btn.onclick 处读取未定义(读取 id)的属性
- javascript - 如何扩展 NextPage 类型以将自定义字段添加到页面组件?
- python - 将列表推导转换为 for 循环