简体   繁体   English

使用VBA从单元格值控制Excel数据透视表的筛选器

[英]Control Filters of Excel Pivot Tables from Cell Values with VBA

I am trying to refresh my powerpivot pivot table based on two cell values. 我正在尝试基于两个单元格值刷新我的powerpivot数据透视表。 End user will use drop down list in cell C17 and C18 to derive a value in cell G17 and G18 (through some excel calculation). 最终用户将使用单元格C17和C18中的下拉列表来导出单元格G17和G18中的值(通过一些excel计算)。 Pivot Table will refresh based on Cell G17 and G18. 数据透视表将根据单元格G17和G18刷新。

I have scripted the code as follow, but it doesn't seem to work as the pivot table doesn't refresh after I select a value from the drop down list in C17 and C18. 我编写了如下代码,但由于在C17和C18的下拉列表中选择一个值后,数据透视表无法刷新,因此似乎无法正常工作。

Sub Worksheet_SelectionChange(ByVal Target As Range)

If Intersect(Target, Range("G17:G19")) Is Nothing Then Exit Sub

Dim pt As PivotTable
Dim FieldHr As PivotField
Dim FieldEndingMin As PivotField
Dim NewHr As String
Dim NewMin As String

Set pt = Worksheets("Calculator").PivotTables("Table1")
Set FieldHr = pt.PivotFields("Hr")
NewHr = Worksheets("Calculator").Range("G17").Value
Set FieldEndingMin = pt.PivotFields("Ending Min")
NewMin = Worksheets("Calculator").Range("G18").Value

With pt
FieldHr.ClearAllFilters
FieldHr.CurrentPage = NewHr
FieldEndingMin.ClearAllFilters
FieldEndingMin.CurrentPage = NewMin
pt.RefreshTable
End With

End Sub

I moved the code from Worksheet_SelectionChange to Worksheet_Change event. 我将代码从Worksheet_SelectionChange移到Worksheet_Change事件。

I added a Union of Ranges, Cells C17:C18 with Cells G17:G19 (is G19 needed ? in your post you mentioned G17:G18). 我在单元格C17:C18和单元格G17:G19中添加了范围Union (是否需要G19?在您提到G17:G18的帖子中)。

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Union(Range("C17:C18"), Range("G17:G19"))) Is Nothing Then Exit Sub

Dim pt                 As PivotTable
Dim FieldHr            As PivotField
Dim FieldEndingMin     As PivotField
Dim NewHr              As String
Dim NewMin             As String

Set pt = Worksheets("Calculator").PivotTables("Table1")
Set FieldHr = pt.PivotFields("Hr")
NewHr = Worksheets("Calculator").Range("G17").Value
Set FieldEndingMin = pt.PivotFields("Ending Min")
NewMin = Worksheets("Calculator").Range("G18").Value

With FieldHr
    .ClearAllFilters
    .CurrentPage = NewHr
End With

With FieldEndingMin
    .ClearAllFilters
    .CurrentPage = NewMin
End With

pt.RefreshTable

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM