根据单元格筛选数据透视表

时间:2018-11-21 17:29:58

标签: excel vba excel-vba pivot-table

我已经使用https://www.mrexcel.com/forum/excel-questions/950078-filtering-pivot-table-based-cell-value.html来创建下面的代码,但是在

上遇到了错误

Set Field = pt.PivotFields("EmployeeName")

是说

Unable to get the PivotFields property of the PivotTable class

即使EmployeeName是我的数据透视表中的一个字段。现在,我在数据模型中确实有2个数据库,它们都具有EmployeeName作为字段,并且通过关系链接。我是否需要指定要使用的数据库以及该怎么做?我的脚本在下面供参考。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

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

'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String

'Here you amend to suit your data
Set pt = Worksheets("2018IndSales").PivotTables("PivotTable4")
Set Field = pt.PivotFields("EmployeeName")
NewCat = Worksheets("2018IndSales").Range("H6").Value

'This updates and refreshes the PIVOT table
With Worksheets("2018IndSales").PivotTables("PivotTable4").PivotFields("EmployeeName")
    .ClearAllFilters
    .PivotFilters.Add Type:=xlCaptionEquals, Value1:=Worksheets("2018IndSales").Range("H6").Value
End With

End Sub

0 个答案:

没有答案