简体   繁体   中英

conditional formatting pivot table vba

I would like to do some conditional formatting in a pivot table and make sure that when the pivot fields are changed, my formatting stays pertinent to what needs to be formatted.

Here is the beginning:

So far I have 2 columns in my dataset: account# and sales. Problem I encounter is that my oPvtItm is empty. The "for each" loop is therefore doing nothing.

Sub condformat1()

Dim ws As Worksheet 
Dim oPvt As PivotTable 
Dim oPvtItm As PivotItem

Set ws = ActiveSheet 
Set oPvt = ws.PivotTables("pv1")


For Each oPvtItm In oPvt.PivotFields("sum of sales").PivotItems

    If oPvtItm > 100000 Then
    oPvtItm.DataRange.Interior.Color = vbYellow
    End If 
Next

End Sub

Once this is solved, I would like to categorise my account (ex. group a,b,c). which might be either a row or column. (lets make it a column to make it simple). I would therefore be willing to analyse only sales of account group "a".

found what I was looking for:

    Sub condformat2()

Dim ws As Worksheet
Dim oPvt As PivotTable
Dim oPvtItm As PivotItem
Dim abc As String


Set ws = ActiveSheet
Set oPvt = ws.PivotTables("pv1")
Set oPvtDataField = oPvt.ColumnFields(1)
abc = "a"

For Each oPvtItm In oPvtDataField.PivotItems
    If oPvtItm = abc Then
        For Each cell In oPvtDataField.PivotItems(abc).DataRange
            If cell.Value > 100000 Then
            cell.Interior.Color = vbYellow
            End If
        Next
    End If
Next

End Sub

Thanks to Doug as well as the author of those sources:

http://www.databison.com/how-to-read-data-from-pivot-table-using-vba/

http://peltiertech.com/referencing-pivot-table-ranges-in-vba/

As mentioned in my comment, I'd consider using actual Conditional Formatting instead of VBA. However, here's some code that will do what you requested:

Sub condformat1()

Dim ws As Worksheet
Dim oPvt As PivotTable
Dim oPvtDataField As PivotField
Dim cell As Range

Set ws = ActiveSheet
Set oPvt = ws.PivotTables("pv1")
Set oPvtDataField = oPvt.DataFields("sum of sales")

For Each cell In oPvtDataField.DataRange
    If cell.Value > 100000 Then
    cell.Interior.Color = vbYellow
    End If
Next
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM