【问题标题】:Find the address of a specific PivotItem查找特定 PivotItem 的地址
【发布时间】:2015-10-07 02:08:20
【问题描述】:

我在RowFields 中有RowField.Name 的值和PivotItem.Name 的值,我想突出显示特定的单元格。但我似乎找不到一种方法可以让我遍历每个可见的 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

最终我想为数据透视表中的特定单元格着色,但我似乎找不到正确的方法。我知道没有索引属性。

有人有想法吗?

【问题讨论】:

  • 如果我对您所追求的理解正确,您可以通过评估 .Visible 属性来测试可见的 PivotItems。示例:If pi.Visible = True Then

标签: excel vba loops pivot pivot-table


【解决方案1】:

在不确切知道您的数据透视表的情况下,我无法准确回答,但我可以告诉您,您希望使用的是 GetPivotData 方法,您可以在其中命名您正在查找的字段和项目获取,它将返回一个范围。

希望这能解决问题!

【讨论】:

  • @Spurious :只需单击链接,您就会得到答案,它可以在 VBA 中使用! ;)
  • 很抱歉现在才回复,但它似乎不适用于我正在寻找的内容。我想获取 Row 项目的地址,我似乎无法使用 GetPivotData 方法获取。
【解决方案2】:

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(纯文本,而不是并行对象),然后使用地址对其进行着色!

【讨论】:

  • 将尝试您的解决方案。
  • 我尝试了您的解决方案,我也为我的目的对其进行了扩展并进行了一些更改,将我的解决方案作为答案发布。
  • @Spurious :您能接受答案以验证您的问题已解决吗?
猜你喜欢
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
相关资源
最近更新 更多