I have a macro, that dynamically generates n number of pivot tables. I am trying to code to ensure that pivot tables that meet a specific set of conditions are highlighted.
My conditions are as follows
- all Values that fall in the Row online and are equal to 2 days (in one color "Orange")
- all Values that fall in the Row online and are greater than 2 days (in one color "Red")
- all cells that are under any header greater than 5 days (in another color "Yellow")
- any time the headers are 5 days or more, then the headers themselves are highlighted in "Yellow"
The code for the same are as follows.
Sub conditionalFormatingPivotTable(ByVal Worksheet As String)
Dim pt As PivotTable, pf As PivotField, pi As PivotItem, d
Dim rngTwoDays As Range, rngFiveDays As Range, rwOnline As Range, c As Range
Set pt = Worksheets("Summary").PivotTables(Worksheet & "PivotTable") 'Setting the pivot table
pt.TableRange1.Interior.ColorIndex = xlNone 'Removing any kind of highlighting that exists
'Start coloring
' x days labels >=5days
Set pf = pt.PivotFields(Worksheet)
For Each pi In pf.PivotItems
d = Val(pi.Name) 'days number only
If d >= 5 Then pi.LabelRange.Resize(2).Interior.Color = vbYellow
If d = 5 Then Set rngFiveDays = pi.DataRange 'for next block
If d = 2 Then Set rngTwoDays = pi.DataRange 'for next block
Next pi
'the rest
Set pf = pt.PivotFields("Order Category")
For Each pi In pf.PivotItems
If pi.Name = "Online" Then
For Each c In pi.DataRange.Cells
If c.Value > 0 And c.column >= rngTwoDays.column Then
If Not Application.Intersect(c, rngTwoDays) Is Nothing Then
c.Interior.Color = XlRgbColor.rgbOrange
Else
c.Interior.Color = vbRed
End If
End If
Next c
Else ' will highlight all other Order categories ("Stock & Store")
For Each c In pi.DataRange.Cells
If c.Value > 0 And c.column >= rngFiveDays.column Then
c.Interior.Color = vbYellow
End If
Next c
End If
Next pi
End Sub
Issue is that when I run the code, some of my PIVOT TABLEs (PT's) are highlighted (where conditions are met) whereas others don't get highlighted even though they meet the condition.
in the below example the pivot in btw got highlighted correctly, whereas the top and bottom PT's missed out on the stock data highlighting
Please help in figuring out where the error is.
