Its been a while since I've worked with VBA, and trying to learn if its possibly to modify this script I found a while back located here and listed below:
h**ps://www.excelcampus.com/vba/hide-unhide-columns-slicer-filter/
Essentially, the script will let you hide and unhide columns based on Pivot Filter criteria and it works pretty well in that you can select multiple items and it will 'filter' or hide and unhide those columns.
And on that link, there is mention also of being able to use it with Multiple Pivot tables which I have done.
But I'm trying to see about modifying the code to use 1 Pivot table with Multiple Filter fields instead of 2 or more pivot tables each with just 1 filter field. Thus, I think I need to somehow loop the pivot table filters of a pivot table.
I'm trying to do this so that when using with slicers, the use of 1 Pivot table will then eliminate those items as you filter different fields.
Attached is a sample file where I have a pivot table with filters for Region, State, City, Market, and Sales. And each of those has defined named range associated with it.
Sub Unhide_Columns(sHeaderRange As String, _
sReportSheet As String)
'Unhide all columns
Worksheets(sReportSheet).Range(sHeaderRange).EntireColumn.Hidden = False
End Sub
Sub Filter_Columns(sHeaderRange As String, _
sReportSheet As String, _
sPivotSheet As String, _
sPivotName As String, _
sPivotField As String _
)
Dim c As Range
Dim rCol As Range
Dim pi As PivotItem
'Loop through each cell in the header range and compare to the selected filter item(s).
'Hide columns that are not selected/filtered out.
For Each c In Worksheets(sReportSheet).Range(sHeaderRange).Cells
'Check if the pivotitem exists
With Worksheets(sPivotSheet).PivotTables(sPivotName).PivotFields(sPivotField)
On Error Resume Next
Set pi = .PivotItems(c.Value)
On Error GoTo 0
End With
'If the pivotitem exists then check if it is visible (filtered)
If Not pi Is Nothing Then
If pi.Visible = False Then
'Add excluded items to the range to be hidden
If rCol Is Nothing Then
Set rCol = c
Else
Set rCol = Union(rCol, c)
End If
End If
End If
'Reset the pivotitem
Set pi = Nothing
Next c
'Hide the columns of the range of excluded pivot items
If Not rCol Is Nothing Then
rCol.EntireColumn.Hidden = True
End If
End Sub
Bookmarks