If I write VBA to automatically filter a pivot table in Excel, it seems that I have to specify each record to be either visible=True or visible=false. Isn't there a way to only specify what I want checked?
For example:
With ActiveSheet.PivotTables("PivotTable1").PivotFields("COB_TITLE")
.PivotItems("CMD GRP").Visible = True
.PivotItems("G1").Visible = True
.PivotItems("G2").Visible = True
End With
instead of
With ActiveSheet.PivotTables("PivotTable1").PivotFields("COB_TITLE")
.PivotItems("CMD GRP").Visible = True
.PivotItems("G1").Visible = True
.PivotItems("G2").Visible = True
.PivotItems("G3/G5/G3 FIRES/REE/G7/HAST/G9").Visible = False
.PivotItems("G4").Visible = False
.PivotItems("G6").Visible = False
.PivotItems("G8").Visible = False
.PivotItems("DIV ENG").Visible = False
End With
I was certain I had recorded a macro at one time that had only what I selected.
So I wrote this string function VisibleList(strSLIDE)
that produces a list like this:
.PivotItems("HHBN").Visible = False
.PivotItems("CMD GRP").Visible = False
.PivotItems("G1").Visible = True
.PivotItems("G2").Visible = True
.PivotItems("G3/G5/G3 FIRES/REE/G7/HAST/G9").Visible = True
.PivotItems("DIV ARTY").Visible = False
.PivotItems("G3 FIRES").Visible = False
.PivotItems("G4").Visible = True
I was hoping I could embed it like this:
strPivotItems = VisibleList("DIV STAFF")
With ActiveSheet.PivotTables("PivotTable1").PivotFields("COB_TITLE")
strPivotItems
End With
I was assuming I could do this like I embed SQL. Is there a way to generate this for VBA?
Not sure this is what you mean, but give the code below a shot:
Option Explicit
Sub FilterPivotItems()
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
Dim PvtItm As PivotItem
' set Pivot Table
Set PvtTbl = ActiveSheet.PivotTables("PivotTable1")
' set Pivot Field to "COB_TITLE"
Set PvtFld = PvtTbl.PivotFields("COB_TITLE")
' loop through all Pivot Items in "COB_TITLE" Pivot Field
For Each PvtItm In PvtFld.PivotItems
' check what is the Pivot item Name
Select Case PvtItm.Name
Case "CMD GRP", "G1", "G2" ' <-- visible Filter Items list
PvtItm.Visible = True
Case Else
PvtItm.Visible = False
End Select
Next PvtItm
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.