获取特定单元格的pivotfields值

时间:2014-01-29 22:48:04

标签: excel vba excel-vba pivot-table

我有来自ssas连接的数据透视表。表格中使用了几个枢轴场。对于这个例子,假设它们是大小,颜色和位置。我的目标是写一些vba,我传递单元格区域并获取相应的pivotfields的值。

例如,如果我传递B6的单元格范围,我想知道该单元格来自size2中color2的location2。如果我传递范围B8,我会得到location1,Color3,Size1等。

enter image description here

到目前为止,这是我能做的。我可以得到该单元格的公式值。以下是B6的结果:GETPIVOTDATA("[Measures].[myValues]",$A$1,"[d size].[size]","[d size].[size].&[Size1]","[d color].[color]","[d color].[color].&[Color2]","[d location].[location]","[d location].[location].&[location2]")使用此代码:

Function xxx(ByVal xyz As Range) As Variant
  xxx = xyz.Formula
End Function
Sub blah()
  MsgBox (xxx(ActiveWorkbook.Sheets("Sheet1").Range("D13")))
End Sub

我还可以遍历pivotfields并获取他们的名字,(但我不知道如何获取他们的值)[Measures].[myValues][d size].[size]等...使用此代码:

With Worksheets("Sheet1").PivotTables(1)
    For i = 1 To .PivotFields.Count
        MsgBox .PivotFields(i).Name
    Next
End With

现在我的问题是,我如何获得特定单元格的枢轴场的值。我希望能够发送B6并返回或访问:location2Color2Size1

修改

越来越近了......我现在可以遍历每个字段并获取其名称和值[d size].[size]&[Size1]等,但现在我希望能够获得Size1或{的值{1}}:

[Size1]

1 个答案:

答案 0 :(得分:1)

改编自RoryA的回答:http://www.mrexcel.com/forum/excel-questions/332678-pivottable-problem.html

'Given a pivottable value cell and a category name, return the category value
'Note: you would need morte code to account for a "page" category 
Function PivotCategoryValue(rngInput As Range, fldName As String) As String

   Dim pc As PivotCell
   Dim pf As PivotField, pi As PivotItem
   Dim rv As String

   On Error Resume Next
   Set pc = rngInput.PivotCell
   On Error GoTo err_handle

   If pc Is Nothing Then
      rv = "Not a pivot cell"
   Else
      Select Case pc.PivotCellType
         Case xlPivotCellValue
            If pc.RowItems.Count Then
               For Each pi In pc.RowItems
                  If pi.Parent.Name = fldName Then
                    rv = pi.Value
                    GoTo done
                  End If
               Next pi
            End If
            If pc.ColumnItems.Count Then
               For Each pi In pc.ColumnItems
                  If pi.Parent.Name = fldName Then
                    rv = pi.Value
                    GoTo done
                  End If
               Next pi
            End If
         Case Else
            rv = "Not a pivot data cell"
      End Select
   End If
done:
   PivotCategoryValue = rv
Exit Function

err_handle:
   PivotCategoryValue = "Unknown error"
End Function