I am working on a series of pivot tables on Excel, for which I would like a particular filter to be automated in the following way: the user inputs a particular value in one cell, and all the filters across the workbook refresh accordingly. I have been reading posts in Stack Exchange which explain how to do it. However, I have come across an issue which I have been unable to solve.
My data comes from an external Microsoft Access database. I have created a connexion between the database and the Excel file; the data is imported to the Excel file where it is displayed as a table tblExcel
. My pivot tables are then linked to this tblExcel
.
To refresh filters, I want to use the following line:
item.Visible = (item.Caption = cd)
where item
is a PivotItems
object and cd
is the value inputted by the user. This line wasn't working, so I wrote the following subroutine to check something:
Sub Test()
check = 0
For Each field In Application.ActiveWorkbook.Worksheets("Sheet1").PivotTables("PivotTable").PivotFields("[tblExcel].[Field1].[Field1]").PivotItems
check = check + 1
Next
MsgBox check
End Sub
It turns out that the MsgBox
returns invariably a 0, for all my fields, like they were empty.
Does anyone know why this is happening? Is it due to my data model structure? How could I circumvent it?
Try the following code, for debug purposes you have an InputBox
, where you write down the Field1 value you want the PIVOT Table to filter to.
Option Explicit
Public Sub Filter_PivotTable_Items()
Dim PvtTbl As PivotTable
Dim pvtFld As PivotField
Dim cd As String
' setting the Pivot Table to a PivotTable Object
Set PvtTbl = ActiveWorkbook.Worksheets("Sheet1").PivotTables("PivotTable")
Application.ScreenUpdating = False
' set Pivot table to show only the selected Project's Data
Set pvtFld = PvtTbl.PivotFields("Field1")
' select manually the value for Field 1 >> for debug purpose
cd = InputBox("Select Item")
Call SelectPivotItem(pvtFld, cd)
End Sub
Public Sub SelectPivotItem(Field As PivotField, cd As String)
Dim Item As PivotItem
On Error GoTo cd_Error
For Each Item In Field.PivotItems
Item.Visible = (Item.Caption = cd)
Next
cd_Error:
If Err.Number = 1004 Then
MsgBox "Item " & cd & " not found !"
Exit Sub
End If
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.