Excel vba: error hiding calculated field in Pivot table - vba

I have written several Subs to show/hide fields in a PivotTable.
Now I am trying to do the same with a calculated field, but I get an error when hiding it.
I took my code from the recorder and the recorder's code also halts on the last line.
I googled the error message, without serious result.
Sub PrRemove()
'remove PR
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.PivotFields("MyField").Orientation = xlHidden '<- here is the error
End Sub
The same code works fine if MyField is a normal field (not a calculated one).
I am using Excel 2007 with SP2.
Any clue ?
EDIT on 17 June 2010: I also tried using pt.DataFields instead of pt.PivotFields, with exactly the same behaviour. The error message says "Unable to set the orientation of the PivotField class".

after much hair pulling i have found a workaround.
if you add more than one pivot field (calculated or otherwise) excel creates a grouped field called Values. you can set the orientation property of PivotField("Values") to xlHidden and it bullets both fields. So if you want to remove a calculated field, just add a non-calculated field, set PivotField("Values").orientation to xlHidden and you're done.
nobody said it would be pretty...

With ActiveSheet.PivotTables("PivottableName").PivotFields("Values")
.PivotItems("CalcFieldName").Visible = False
End With

I wanted to easily remove data fields (calculated fields or not), like it would be done manually.
And I finally found this solution (Excel 2010) :
Set pt = ActiveSheet.PivotTables("mypivottable")
For Each pi In pt.DataPivotField.PivotItems
pi.Visible = False
Next

Well, I will give you the confirmation you need. It seems using the Orientation property on a "Calulated Field" just does not work, and I would have to agree this is a bug and not a common "usage" error. I was able to duplicate "hiding/showing" the field without having to remove ("Delete") the calculated field. This allows the user to physically drag the calculated field from the field list after you have progammatically "hidden" the field. This is not a bad solution because it duplicates the user-interface. (Using Excel 2003.)
'2009.09.25 AMJ
'work around for
' 1004, Unable to set the Orientation property of the PivotField class
'when setting orientation property to hidden of calculated field, as in
' ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Field1").Orientation = xlHidden
Public Sub Hide()
'hide the data without removing the calculated field
' this allows the user to physically drag the
' calculated field from the field list once we
' have "hidden" it programmatically.
' if we use the "delete" method, the field is removed
' from the pivot table and the field list
Dim oWS As Worksheet
Dim oPT As PivotTable
Dim oPF As PivotField
Dim oPI As PivotItem
Set oWS = ActiveSheet
Set oPT = oWS.PivotTables(1)
For Each oPF In oPT.DataFields
If oPF.SourceName = "Field1" Then
'Stop
Exit For
End If
Next
Set oPI = oPF.DataRange.Cells(1, 1).PivotItem
'oPI.DataRange.Select
oPI.Visible = False
End Sub
Public Sub Show()
'show just reads the pivot field to the data fields
Dim oWS As Worksheet
Dim oPT As PivotTable
Dim oPF As PivotField
Set oWS = ActiveSheet
Set oPT = oWS.PivotTables(1)
For Each oPF In oPT.PivotFields
If oPF.SourceName = "Field1" Then
'Stop
Exit For
End If
Next
oPT.AddDataField oPF
End Sub
[original answer]
Most likely you cannot hide this item because it is the last visible item. Instead, try removing it.

Here is a little workaround I discovered today, again not very elegant but at least it doesn't need much code, it will hide ALL the fields and you will need to reshow the ones you want after:
objTable.DataPivotField.Orientation = xlHidden
You may run into an error if excel for some reason thinks the datapivotfield is empty, but to fix this just add in another field as a datafield right before the above statement. Also make sure its the letter l not the number 1 in xlHidden vba's default font has them looking very very similar.
Happy Coding

It seems that to hide a calculated field you need to first hide a pivot field called "Values".
PivotTable(1).PivotFields("Values").Orientation = xlHidden
For Each PF In PT.DataFields
PF.Orientation = xlHidden
Next PF
I'm assuming that field only seem to exist if you've got two or more fields in your xlDataField position.
Thanks Alinboss for pointing me in the right direction. I was sure I tried your method before and failed - turns out the order is important!
P.s. Your code still does not work with only one calculated data field

Laurent Bosc's code checks out so I voted it up. My full code includes adding data after hiding it all. The code is placed on Sheet1(Sheet1).
Private Sub Refresh_Pivot()
Dim NewMetric As String
Dim pt As PivotTable, objDataField As Object
NewMetric = "your_custom_metric"
'-------update pivot table 1, hide all elements including calculated field----
Application.EnableEvents = False
Set pt = Sheet1.PivotTables("PivotTable1")
For Each Pi In pt.DataPivotField.PivotItems
Pi.Visible = False
Next
'--------add a new data field to the pivot table----------------------------
With pt
.AddDataField.PivotFields(NewMetric), "Sum of " & NewMetric, xlSum
End With
Application.EnableEvents = True
End Sub

I don't think this is an excel bug, I think it's a 'feature'. ;-)
Re: #AMissico, there is no problem in excel hiding all of the fields in a pivot table, but he may be talking about items - you can't hide the last item in a pivot field.
This is the code I routinely use to do what you are trying to do. These macros were developed on Excel 2002 & 2003. I don't hide CalculatedFields, I delete them.
' Hide all fields.
' #param ThePivotTable to operate upon.
Sub HidePivotFields(ByVal ThePivotTable As PivotTable)
Dim pField As PivotField
For Each pField In ThePivotTable.CalculatedFields
pField.Delete
Next pField
For Each pField In ThePivotTable.PivotFields
pField.Orientation = xlHidden
Next pField
Set pField = Nothing
End Sub
' Removes FieldName data from ThePivotTable
Sub HideField(ByVal ThePivotTable As PivotTable, _
ByVal FieldName As String)
If FieldExists(ThePivotTable, FieldName) = True And _
CalculatedFieldExists(ThePivotTable, FieldName) = False Then
ThePivotTable.PivotFields(FieldName).Orientation = xlHidden
End If
End Sub
' Returns True if FieldName exists in ThePivotTable
'
' #param ThePivotTable to operate upon.
' #param FieldName the name of the specific pivot field.
Function FieldExists(ByVal ThePivotTable As PivotTable, _
ByVal FieldName As String) As Boolean
Dim pField As PivotField
For Each pField In ThePivotTable.PivotFields
If pField.SourceName = FieldName Then
FieldExists = True
Exit For
End If
Next pField
Set pField = Nothing
End Function
' Checks if the field FieldName is currently a member of the
' CalculatedFields Collection in ThePivotTable.
' #return True if a CalculatedField has a SourceName matching the FieldName
' #return False otherwise
Function CalculatedFieldExists(ByVal ThePivotTable As PivotTable, _
ByVal FieldName As String) As Boolean
Dim pField As PivotField
CalculatedFieldExists = False
For Each pField In ThePivotTable.CalculatedFields
If pField.SourceName = FieldName Then
CalculatedFieldExists = True
End If
Next pField
Set pField = Nothing
End Function
' Returns a Pivot Field reference by searching through the source names.
'
' This function is a guard against the user having changed a field name on me.
' #param ThePivotTable to operate upon.
' #param FieldName the name of the specific pivot field.
Function GetField(ByVal ThePivotTable As PivotTable, _
ByVal FieldName As String) As PivotField
Dim pField As PivotField
For Each pField In ThePivotTable.PivotFields
If pField.Name <> "Data" Then
If pField.SourceName = FieldName Then
Set GetField = pField
Exit For
End If
End If
Next pField
Set pField = Nothing
End Function
' Counts the number of currently visible pivot items in a field.
' #param ThePivotItems the collection of pivot itemns in a field.
' #return the count of the visible items.
Function PivotItemCount(ByVal ThePivotItems As PivotItems) As Long
Dim pItem As PivotItem
Dim c As Long
For Each pItem In ThePivotItems
If pItem.Visible = True Then c = c + 1
Next pItem
PivotItemCount = c
Set pItem = Nothing
End Function
' Hides a single pivot item in a pivot field, unless it's the last one.
' #param FieldName pivot field containing the pivot item.
' #param ItemName pivot item to hide.
Sub HidePivotItem(ByVal ThePivotTable As PivotTable, _
ByVal FieldName As String, _
ByVal ItemName As String)
Dim pField As PivotField
Set pField = GetField(ThePivotTable, FieldName)
If Not pField Is Nothing Then
If PivotItemCount(pField.PivotItems) > 1 Then
pField.PivotItems(ItemName).Visible = False
End If
End If
Set pField = Nothing
End Sub

I am having the exact same problem as you.
It looks like I'm going to have to delete the calculated field and readd it rather than hiding/showing it.

I accidentally discovered a workaround to this the first time I attempted to hide a calculated field, so thought I would share it here:
Instead of modifying the orientation property, you can instead instruct the code to select the cell in the pivot table that contains the title of the calculated field you want to hide, and then delete the selection. This works as long as you have another datafield already in the table. Example below:
Scenario: Pivot table covers the range A1:G10. Calculated field "Margin" is already in the table, and you want to add the data field "Sales" and remove the "Margin" calc field.
Code to execute:
'Add Sales data field
ActiveSheet.PivotTables(Pname).AddDataField ActiveSheet.PivotTables( _
Pname).PivotFields("SALES"), "Sum of SALES", xlSum
'At this point, the datafield titles are in vertically adjacent rows, named "Sum
'of Margin" and "Sum of Sales" at locations B3 and B4 respectively.
'Remove the "Sum of Margin" calculated field
Range("B3").Delete
Not sure why this works, but I'm glad we at least have this to work with!

Fortunately there is a very easy way to hide a datafield. You were all wrong mistakeing pivotfields with datafields. I'm presenting a piece of code that empties a pivot table no matter how many pivot fields/data fields were initially in the pivot :
Sub Macro1()
Dim p As PivotTable
Dim f As PivotField
Set p = ActiveSheet.PivotTables(1)
For Each f In p.PivotFields
If f.Orientation <> xlHidden Then
f.Orientation = xlHidden
End If
Next f
For Each f In p.DataFields
If f.Orientation <> xlHidden Then
f.Orientation = xlHidden
End If
Next f
End Sub

Have you changed the name of the calculated field? Was it originally 'Sum of MyField'? Try looking at the SourceName property and if it's different using that.
Have you tried pt.CalculatedFields("MyField").Orientation = xlHidden ?

I know it is kind of late, but i see that this problem has not been answered confidently yet and i was facing the same problem having hard time to find useful info. So, i hope this post may help somebody...
If you have your data stored in data model, then instead of PivotFields, use CubeFields .
I had the same problem and i experimented with a simple workbook which did not had a data model and my code worked perfectly (using PivotFields).
It only returned error in the workbook with the data model.
So, i made this change and boom! it worked!
My suggestion is to use the following code:
Sub PrRemove()
'remove PR
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.CubeFields("MyField").Orientation = xlHidden '<- here is the error
End Sub

Thanks to #user4709164 answer i got this code, its working perfectly for me:
my pivot columns all ends with X or Y to indicate axis so i use the last char for field caption.
Public Sub PivotFieldsChange()
Dim ValType As String, param As String
Dim pf As PivotField
Dim pt As PivotTable
Application.ScreenUpdating = False
Sheet = "mysheet"
'select between % calculated column or normal column
If Range("Z1").Value = 1 Then
ValType = "%"
Else: ValType = ""
End If
Application.EnableEvents = False
For Each pt In Sheets(Sheet).PivotTables
Select Case pt.Name
Case "case1": param = "param1"
Case "case2": param = "param2"
Case "case3": param = "param3"
Case Else: GoTo line1
End Select
pt.PivotFields("Values").PivotItems("X").Visible = False
pt.PivotFields("Values").PivotItems("Y").Visible = False
pt.PivotFields (param & ValType & "_X")
pt.PivotFields(param & ValType & "_X").Orientation = xlDataField
pt.PivotFields (param & ValType & "_Y")
pt.PivotFields(param & ValType & "_Y").Orientation = xlDataField
For Each pf In pt.DataFields
pf.Function = xlAverage
pf.Caption = Right(pf.Caption, 1)
Next
line1:
Next pt
Application.EnableEvents = True
End Sub

Related

How to divide all values in a pivot table column by a constant

I would like to scale (divide, multiply) a pivot tables value by some constant that I add into the pivot tables sheet, like so:
The problem of automatically updating the pivot tables values as the values in the original data change I already solved with this code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveWorkbook.Worksheets("Sheet4").PivotTables(1).PivotCache.Refresh
End Sub
I have tried simply doing it inside a worksheet_change() method, but this gives type mismatch error:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("C4:C5"), Range(Target.Address)) Is Nothing Then
Application.EnableEvents = False
'Target.Value = Target.Value * Range("B1").Value <-- gives error of type mismatch
MsgBox VarType(Target.Value)
MsgBox VarType(Range("B1").Value)
Application.EnableEvents = True
End If
End Sub
Here is one way. When the event WorkSheet_Change fires, check if your scaling value (in B1) has changed. If so, re-write the calculated field:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("B1"), Range(Target.Address)) Is Nothing Then
ActiveWorkbook.Worksheets("Sheet4").PivotTables(1).CalculatedFields("ScaledField"). _
StandardFormula = "=Kaina*" & Range("B1").Value
End If
End Sub
You'll need to create a calculated field called ScaledField (or give it your own name - just change the code too) and you might want to change the formula if you don't want to scale [Kaina], but something else.
PS. If the value isn't [Kaina], but [Kaina Sausis] then the formula would require single quotes to wrap the field name:
StandardFormula = "='Kaina Sausis'*" & Range("B1").Value
Manipulating the value of data fields directly in the pivot table is not possible (try to manually change a value or with VBA and you get an error message).
It's possible to overwrite values of row fields, but that's a bit strange (they will stay like this after and not update anymore unless you by coincidence entered a valid value).
For calculations you can add a calculated field. If the value is constant and the value doesn't need to be taken from a Range just add a calculated field manually (Analyze > Fields ... > Calculated Field...) and enter the constant value in the formula.
Unfortunately calculated fields cannot reference ranges so if you really have to use the value from a Range in the formula of the calculated field you can use this VBA code (it adds a calculated field or updates the formula if the field already exists, that would be of use if the value is not constant):
' You prolly have to call this only once as you are using a constant value.
' If not add to your worksheet change event
' Modify hardcoded values if needed
Sub createOrUpdateField()
Dim fldFormula As String
' Construct the formula to use
fldFormula = "= Kaina Sausis / " & ActiveSheet.Range("B1").Value2
addOrUpdateCalculatedField _
ActiveSheet.PivotTables(1), _
"Kaina Sausis Calc", fldFormula, "0.00"
End Sub
' In case you want to remove the calculated field use this
' Or use the interface (Analyze > Fields ... > Calculated Field...)
Sub deleteField()
pt.PivotFields("Kaina Sausis Calc").Delete
End Sub
' Add a calculated field to pivot table or update formula if it already exists.
' Args:
' pt (PivotTable): The pivot table object
' fldName (String): Name to use for the field
' fldFormula (String): Formula to use for calculation
' fldFormat (String): Number format to use
Sub addOrUpdateCalculatedField(pt As PivotTable, fldname As String, _
fldFormula As String, fldFormat As String)
Dim wks As Worksheet
Dim ptfld As PivotField
' Try to reference the field to check if it already exists
On Error Resume Next
Set ptfld = pt.PivotFields(fldname)
On Error GoTo 0
If ptfld Is Nothing Then
' Field doesn't exist, add it
Set ptfld = pt.CalculatedFields.Add(name:=fldname, formula:=fldFormula)
With ptfld
.Caption = fldname
.NumberFormat = fldFormat
.Orientation = xlDataField
.Function = xlSum
End With
Else
' Field already exists, change the formula only
ptfld.StandardFormula = fldFormula
End If
Set wks = Nothing
Set pt = Nothing
Set ptfld = Nothing
End Sub

OLAP Cube Pivot Field Hide Items Dynamically

My goal is to use VBA to dynamically hide all items in a PivotTable field list except for an array of items stored in a separate table. The catch is it's an OLAP cube so I have to use the Cube field method. Also I am only aware of a way to hide specific items. What I want to do is hide everything except specific items.
I am getting an
Application Defined or Object Related Error
on the line with .HiddenItemsList
I know I am way off on syntax but quite lost at this point.
Public Sub FilterRd()
Dim arCC As Variant
Dim pfCostCenterCode As PivotField
Dim PF As PivotField
Dim PI As PivotItem
arCC = Worksheets("CCs").ListObjects("tblCCs").DataBodyRange.Value
arCC = Application.Transpose(arCC)
Set pfCostCenterCode = Worksheets("RDA").PivotTables("PTccs").PivotFields("[DCC].[CCC].[CCC]")
a = Filter_PivotField(pfCostCenterCode, arrCC)
End Sub
Private Function Filter_PivotField(pvtField As PivotField, varItemList As Variant)
Dim i As Long
' On Error GoTo ErrorHandler:
Application.ScreenUpdating = False
With pvtField
.ClearAllFilters
.CubeField.IncludeNewItemsInFilter = True
End With
For i = LBound(varItemList) + 1 To UBound(varItemList)
pvtField.HiddenItemsList = Array("[DCC].[CCC].&" & varItemList(i) & "]")
Next i
ErrorHandler:
MsgBox "Error while trying to process item: " & varItemList(i)
End Function

VBA macro to change filters in pivot table

I'm trying do automate a daily report and therefore I want to create two buttons which change the filters of three pivot tables. In detail the buttons shall change the day which is shown. The first filters on yesterday the second one is a reset button do clear all filters and show all days.
The "Resest"-Button is working but the "Yesterday"-Button not.
At the moment the macro looks like that:
Private Sub CommandButton2_Click()
MsgBox ActiveSheet.Range("B1")
With ActiveSheet.PivotTables("Detail_Digital").PivotFields("Tag").CurrentPage = _
ACtiveSheet.Range("B1").Value
End With
End Sub
I've also tried PivotFilters.Add _ , Type:=xlDateYesterday but that isn't working either.
Any suggestions?
Try the code below, it should work, unless your "Date" is formatted differently between the Pivot's data source and Range("B1").
Note: try to avoid using ActiveSheet, instead use referenced objects. In the case below, replace Worksheets("Sheet1") with your sheet's name.
Code
Option Explicit
Private Sub CommandButton2_Click()
Dim PvtTbl As PivotTable
Dim PvtItm As PivotItem
' set the Pivot Table
Set PvtTbl = Worksheets("Sheet1").PivotTables("Detail_Digital")
With PvtTbl
.PivotFields("Tag").ClearAllFilters ' <-- clear all filters to "Tag"
'Debug.Print Worksheets("Sheet1").Range("B1").Value
For Each PvtItm In .PivotFields("Tag").PivotItems
If PvtItm.Name = Worksheets("Sheet1").Range("B1").Value Then
PvtItm.Visible = True
Else
PvtItm.Visible = False
End If
Next PvtItm
End With
End Sub

VBA multiple checkboxes to control multiple pivot tables

again I need little help which I will greatly appreciate.
Basically, on my dashboard page I have couple of checkboxes that control numerous of pivot tables in the background.
I have checkboxes that are called "definite", "tentative", "pending,", ... and also corresponds to values in pivot fields.
and I have numerous of pivot tables called: "Hidden_1" or "Hidden_2" in different sheets but all with the same structure.
My idea was that If someone checked "definite", it will be selected in all pivot pivot tables in fields called "Status". If someone "unchecked" this checkbox, the pivots will react.
To do so I used a code that I create before and it was working well:
Sub checkbox1()
Application.ScreenUpdating = False
On Error Resume Next
Dim pt As PivotTable, wks As Worksheet
For Each wks In ActiveWorkbook.Worksheets
For Each pt In wks.PivotTables
With pt
If .Name = "Hidden_1" Or .Name = "Hidden_2" Then
.PivotFields("Status").CurrentPage = "definite"
End If
End With
Next pt
Next wks
Application.ScreenUpdating = True
End Sub
However, this code selects only one value, so I can't have selected both "definite" and "pending" if someone checked those boxes. Right now all checkboxes has a separate code assigned where only .CurrentPage = "checkboxname" was changed..
I have two questions:
1) what is the best way to select multiple values. E.g. if checked boxes "definite" and "pending" are checked, pivot tables should have selected two values "definite" and "pending" selected in the "Status" field
2) what is the best way to "dis-select" the value? Right now, my procedure checkbox1 is running everytime that the checkbox is clicked. And I want it to run only when I am "checking" it.
Right now I am trying to link the checkbox with cell, e.g. "definite" has H10, so my code starts with the line:
If Range("H10").Value = True Then
'code to select the value in "Status" field
Else
'code to unselect the value in "Status" field
End If
I should also noted that I couldn't use ActiveX Checkbox because I had error: "cannot insert object" and I used form controls. I read that this error is somehow connected with a patch that I have installed.
Thank you all for your help,
Matt
I worked on it and found such a solution:
Sub checkbox1()
Dim choice1, choice2, choice3, choice4, choice5, choice6, choice7
Dim oPI As PivotItem
Dim pt As PivotTable, wks As Worksheet
If Sheets("Hidden").Range("B6").Value = "True" Then
choice1 = "Definite"
End If
If Sheets("Hidden").Range("B7").Value = "True" Then
choice2 = "Tentative"
End If
If Sheets("Hidden").Range("B8").Value = "True" Then
choice3 = "Hold/Option"
End If
If Sheets("Hidden").Range("B9").Value = "True" Then
choice4 = "Pending"
End If
If Sheets("Hidden").Range("B10").Value = "True" Then
choice5 = "Waitlist"
If Sheets("Hidden").Range("B11").Value = "True" Then
choice6 = "Lost"
End If
If Sheets("Hidden").Range("B12").Value = "True" Then
choice7 = "Cancelled"
End If
Sheets("Hidden_pivot1").PivotTables("Hidden_1").PivotFields("SalesStatus").ClearAllFilters
Sheets("Hidden_pivot1").PivotTables("Hidden_3").PivotFields("SalesStatus").ClearAllFilters
Sheets("Hidden_pivot2").PivotTables("Hidden_2").PivotFields("SalesStatus").ClearAllFilters
Sheets("Hidden_pivot2").PivotTables("Hidden_4").PivotFields("SalesStatus").ClearAllFilters
For Each wks In ActiveWorkbook.Worksheets
For Each pt In wks.PivotTables
With pt
If .Name = "Hidden_1" Or .Name = "Hidden_2" Or .Name = "Hidden_3" Or .Name = "Hidden_4" Then
For Each oPI In pt.PivotFields("SalesStatus").PivotItems
Select Case oPI.Name
Case choice1, choice2, choice3, choice4, choice5, choice6, choice7
Case Else
oPI.Visible = False
End Select
Next
End If
End With
Next pt
Next wks
End Sub
This work but is so slow. It would be better if the macro could add and delete those items, instead of re-creating the entire choice.

Update and filter pivot with VBA - Wildcard filter

I want to clear the prevoius filter on pivotfield Invoicenr, update a pivot table, and not show certain items.
I want to show Everything but the items that have a Invoicenr that begins with PO* (seems that * can't be used in VBA?).
Besides this I want to see everything else and the Invoicenr that starts with PO and contains OH.
See my attempt below:
Sub Macro2()
'
' Macro2 Macro
'
ThisWorkbook.RefreshAll
'Worksheets("Pivot").Select
'ActiveSheet.PivotTables("PIVOT1").RepeatAllLabels xlRepeatLabels
ActiveSheet.PivotTables("PIVOT1").PivotFields("Invoicenr"). _
ClearLabelFilters
With ActiveSheet.PivotTables("PIVOT1").PivotFields("invoicenr")
.PivotItems("PO").Visible = False
End With
End Sub
If I'm understanding the conditions correctly, this should get you the results you want for the first case...
Show All Items except ones that begin with "PO" :
Sub ShowAllButPO()
Dim ws As Worksheet
Dim pvtTable As PivotTable
Dim pvtField As PivotField
Dim pvtItem As PivotItem
Set ws = ActiveSheet
Set pvtTable = ws.PivotTables("PIVOT1")
Set pvtField = pvtTable.PivotFields("Invoicenr")
pvtTable.RefreshTable
pvtTable.ClearAllFilters
For Each pvtItem In pvtField.PivotItems
If Left(UCase(pvtItem), 2) = "PO" Then
pvtItem.Visible = False
End If
Next
End Sub
And this should cover the second condition...
Show All Items in "invoicenr" that start with "PO" and also contain "OH" :
Sub ShowOnlyPO()
Dim ws As Worksheet
Dim pvtTable As PivotTable
Dim pvtField As PivotField
Dim pvtItem As PivotItem
Set ws = ActiveSheet
Set pvtTable = ws.PivotTables("PIVOT1")
Set pvtField = pvtTable.PivotFields("Invoicenr")
pvtTable.RefreshTable
pvtTable.ClearAllFilters
For Each pvtItem In pvtField.PivotItems
If Left(UCase(pvtItem), 2) = "PO" And InStr(UCase(pvtItem), "OH") > 0 Then
pvtItem.Visible = True
Else
pvtItem.Visible = False
End If
Next
End Sub
I'm less sure about what you wanted for the second condition. Your wording "i want to see Everything else and the invoicenr that starts with PO and contains "OH"" wasn't completely clear to me.
If you could clarify what you mean by "Everything else and invoicenr that starts with PO.. etc etc" then I can update my code if needed.
Also, if those two code blocks end up getting you what you want, then you could just assign each macro to its own button in your worksheet. That way, you could just toggle the two scenarios without having to open the VBEditor to run the code. If you are unsure how to do this, check out this link
Use this code:
Sub Except_PO()
Dim var As Variant
var = "PO*"
ActiveSheet.PivotTables("Pivot1").PivotFields("Invoicenr").ClearAllFilters
ActiveSheet.PivotTables("Pivot1").PivotFields("Invoicenr").PivotFilters. _
Add Type:=xlCaptionDoesNotEqual, Value1:=var
End Sub
Sub POwithOH()
Dim var As Variant
var = "PO*OH*"
ActiveSheet.PivotTables("Pivot1").PivotFields("Invoicenr").ClearAllFilters
ActiveSheet.PivotTables("Pivot1").PivotFields("Invoicenr").PivotFilters. _
Add Type:=xlCaptionEquals, Value1:=var
End Sub
Then make 2 command buttons with this code
filtering All EXCEPT PO
Private Sub CommandButton1_Click()
Call Except_PO
End Sub
Filtering data starting with PO and contains OH
Private Sub CommandButton2_Click()
Call POwithOH
End Sub
So if you click CommandButton1, your pivot will filter those data that don't start with PO.
And when you click CommandButton2, your pivot will filter all data that starts with PO AND contains OH.