Excel 2013 VBA从单个单元格中过滤多个透视表不起作用

时间:2018-01-02 16:48:22

标签: excel vba excel-vba

第一次发帖。

我有一个Excel 2013电子表格,上面有三个透视图。我试图通过引用同一张纸上的单元格来自动更新它们。 VBA代码是:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'This line stops the worksheet updating on every change, it only updates when cell B1 is touched
If Intersect(Target, Range("B1")) Is Nothing Then Exit Sub

'Set the Variables to be used and assigns their values

Dim WS1 As Worksheet: Set WS1 = ActiveWorkbook.Worksheets("PIVOT")
Dim PT1 As PivotTable: Set PT1 = WS1.PivotTables("pgmTable1")
Dim PT2 As PivotTable: Set PT2 = WS1.PivotTables("pgmTable2")
Dim PT3 As PivotTable: Set PT3 = WS1.PivotTables("pgmTable3")

Dim PF1 As PivotField: Set PF1 = PT1.PivotFields("REPORTING_DATE")
Dim PF2 As PivotField: Set PF2 = PT2.PivotFields("REPORTING_DATE")
Dim PF3 As PivotField: Set PF3 = PT3.PivotFields("REPORTING_DATE")

Dim filterCell As Date

'This reassigns the filter to the sheet-defined value
filterCell = WS1.Range("B1").Value

'This updates and refreshes the PIVOT tables
With PT1
PF1.ClearAllFilters
PF1.CurrentPage = filterCell
PT1.RefreshTable
End With

With PT2
PF2.ClearAllFilters
PF2.CurrentPage = filterCell
PT2.RefreshTable
End With

With PT3
PF3.ClearAllFilters
PF3.CurrentPage = filterCell
PT3.RefreshTable
End With

End Sub

Lua/Examples

它正在返回

  

运行时错误'1004':应用程序定义的错误或对象定义的错误

Here's the spreadsheet:

此代码适用于过去包含单个数据透视表的工作表。我是一个相对的小伙子,已经把这个混在一起了。我确信有更优雅的方式来使用for循环进行此更新。

另外,我尝试将这些数据透视表拆分到自己的工作表上但没有成功。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

mmm,你为什么不在Excel中使用“Slicer”?您可以轻松连接多个数据透视表,而不是使用VBA。

  1. 单击数据透视表中的任何单元格。
  2. 转到“分析”
  3. 寻找“插入切片器”
  4. 选择要用作过滤器的字段
  5. 右键单击切片器
  6. 查找“报告连接...”并将要过滤的所有数据透视表连接到该切片器。
  7. 注意:所有数据透视表都需要相同的来源。

    我做了Tutorial。它是西班牙语,但我使用的是英文Excel版本。