如何合并两个Worksheet_Change事件实现双数据透视表动态筛选
合并后可直接使用的VBA代码
Private Sub Worksheet_Change(ByVal Target As Range) Dim xPTable As PivotTable Dim xPFile As PivotField Dim xStr As String On Error Resume Next Application.ScreenUpdating = False ' 触发L3:L4区域修改时更新PivotTable1的Machine字段筛选 If Not Intersect(Target, Range("L3:L4")) Is Nothing Then Set xPTable = Worksheets("Summary").PivotTables("PivotTable1") Set xPFile = xPTable.PivotFields("Machine") xStr = Target.Text xPFile.ClearAllFilters xPFile.CurrentPage = xStr ' 触发P16:P17区域修改时更新PivotTable2的Machine字段筛选 ElseIf Not Intersect(Target, Range("P16:P17")) Is Nothing Then Set xPTable = Worksheets("Summary").PivotTables("PivotTable2") Set xPFile = xPTable.PivotFields("Machine") xStr = Target.Text xPFile.ClearAllFilters xPFile.CurrentPage = xStr End If Application.ScreenUpdating = True End Sub
实现说明
- 两个独立的触发判断分支完全保留了原有两段代码的筛选逻辑,无需调整原有单元格配置和透视表设置
- 将屏幕更新开关移到最外层,避免重复开关,运行效率更高
- 两个触发区域互不干扰,只有修改对应区域的内容才会触发对应透视表的筛选更新
内容的提问来源于stack exchange,提问作者Sande
相关产品推荐
相关产品推荐

