我想从Row项目中选择与一个特定的PivotField关联的所有数据单元格,我该怎么做?
我的数据看起来像这样:
Sum of x Sum of y Sum of z
Class1 2.5 1 2
*Name1 *1 *0 *0
*Name2 *1 *1 *1
*Name3 *.5 *0 *1
Class2 3.8 2.6 2
*NameA *1 *1 *0
*NameB *0.8 *0 *1
*NameC *1 *0.6 *0
*NameD *1 *1 *1
现在,我只想选择前面带有*的数据并执行条件格式设置-如果单元格值小于1,则突出显示该单元格。如果大于1,则用其他颜色突出显示。如上所述,我在选择所需的数据范围时遇到了麻烦。
尝试输入以下代码:(错误:对象不支持此属性或方法)
Sub formatPivotTable()
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Set pt = ActiveSheet.PivotTables("test")
Set pf = pt.PivotFields("Name").PivotItems.DataRange.Select (error: object doesnt support this property or method)
With pf.DataRange
.Interior.ColorIndex = 6
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=1"
With .FormatConditions(1)
.Interior.ColorIndex = 3
End With
.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=1"
With .FormatConditions(2)
.Interior.ColorIndex = 4
End With
End With
End Sub
任何帮助将不胜感激。
答案 0 :(得分:1)
希望这就是您想要的。
以下代码:
pivotItem
中的每个pivotField
,并使用namesRange
建立Union
。 namesRange
对应于屏幕截图中的$B$5:$B$7,$B$9:$B$12
。Intersect
,namesRange.EntireRow
和DataBodyRange
来获得condFormRange
。 condFormRange
对应于屏幕截图中的$B$5:$D$7,$B$9:$D$12
。从那里开始,条件格式就已经存在。
Sub FormatPivotTable()
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("test")
Dim pf As PivotField
Set pf = pt.PivotFields("Name")
Dim pi As PivotItem
Dim namesRange As Range
For Each pi In pf.PivotItems
If namesRange Is Nothing Then
Set namesRange = pi.DataRange
Else
Set namesRange = Union(namesRange, pi.DataRange)
End If
Next pi
Debug.Print namesRange.Address ' returns $B$5:$B$7,$B$9:$B$12
If Not namesRange Is Nothing Then
Dim condFormRange As Range
Set condFormRange = Intersect(namesRange.EntireRow, pt.DataBodyRange)
Debug.Print condFormRange.Address ' returns $B$5:$D$7,$B$9:$D$12
With condFormRange
.Interior.ColorIndex = 6
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=1"
With .FormatConditions(1)
.Interior.ColorIndex = 3
End With
.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=1"
With .FormatConditions(2)
.Interior.ColorIndex = 4
End With
End With
End If
End Sub