我有RowField.Name
的值和PivotItem.Name
中RowFields
的值,我想突出显示特定的单元格。但我似乎无法找到一种允许我遍历每个可见RowField的方法。
理想情况下,我想要这样的事情:
Sub LoopThroughPivotAndFindValue()
dim pt as PivotTable, pi as PivotItem, pf as PivotField
Set pt = wb.PivotTables("PivotTableNo1")
For each pf in pt.PivotFields
For each pi in pf.PivotItems
If pf.Name = "Test" And pi.Name = "Value" Then
'Ideally here would be the output of the address within the sheet
End If
Next pi
next pf
End Sub
最终我想在数据透视表中为特定单元格着色,但我似乎无法找到正确的方法。我没有注意到的索引属性。
有想法的人吗?
答案 0 :(得分:2)
如果不确切知道您的数据透视表的样子,我无法准确回答,但我可以告诉您,您希望使用的是GetPivotData方法,您可以将该字段命名为和你想要获得的项目,它将返回一个范围。
希望这可以解决问题!!
答案 1 :(得分:1)
UDF也很有用,这对你来说可能是一个好的开始:
Sub test_Spurious()
MsgBox LoopThroughPivotAndFindValue("Test", "Value")
End Sub
这是功能:
Function LoopThroughPivotAndFindValue(ByVal PivotFieldName As String, ByVal PivotItemName As String) As String
Dim pT As PivotTable, _
pI As PivotItem, _
pF As PivotField, _
FoundIt As Boolean
FoundIt = False
Set pT = ActiveSheet.PivotTables(1)
For Each pF In pT.PivotFields
For Each pI In pF.PivotItems
If pF.Name = PivotFieldName And pI.Name = PivotItemName Then
'Ideally here would be the output of the address within the sheet
On Error GoTo ErrHandler
FoundIt = True
LoopThroughPivotAndFindValue = pI.LabelRange.Address
Exit For
On Error GoTo 0
End If
Next pI
Next pF
If FoundIt Then GoTo FreeObjects
ErrHandler:
LoopThroughPivotAndFindValue = "Nothing"
FreeObjects:
Set pT = Nothing
End Function
所以,我说最好的方法是将结果存储到临时变量中并检查它是否为Nothing
(以纯文本形式,而不是并行对象)然后使用地址为它上色!