在给定第一行字段中的特定枢轴项的情况下列出第二行字段(多行字段)的excel轴项

时间:2015-10-02 22:21:33

标签: vba excel-vba excel

我搜索了很长时间,但仍然没有定论。假设我有一个包含2个行标签和1个数据变量的数据透视表,如下所示:

Rowlabel1 Rowlabel2 Sum of value
   a          A          1
              B          2
              C          3
   d          D          4
   e          E          5

我希望能够在给定特定Rowlabel2的情况下列出Rowlabel1的透视项,以便循环获取"A"" B" "C",然后连结到"ABC"。无论我尝试什么,它只输出所有枢轴项"ABCDE"

由于实际数据更复杂,因此无法手动执行。它还有3个行标签而不是2个标签。

不知道它是否会有所帮助,但解决方案也可以使用这些值。例如,当“Rowlabel2”为<= 3时,返回值为letter的{​​{1}}项。

感谢您提出任何意见!!

1 个答案:

答案 0 :(得分:0)

Sub getPiv()

Dim piv As PivotTable

'change this to whatever range and sheet names your pivottable is
Set piv = ThisWorkbook.Sheets("SecondTable_Output").Range("A3").PivotTable

Dim r As Range
Dim dr As PivotItem

'this captures your first entry in rowlabel1 - change as necessary
Set dr = piv.PivotFields(1).PivotItems(1)

Dim str As String
str = ""

'the macro won't work if the item is collapsed, so we set showDetail to true to expand it
If dr.ShowDetail = False Then
    dr.ShowDetail = True
End If

With dr
    'address what seems to be a bug(??) where if there are more than one data value columns,
    'the datarange appears to shift one row down
    If .DataRange.Columns.Count > 1 Then
        'here we shift back from the datarange to the 2nd column of the pivottable
        Set r = .DataRange.Offset(-1, -(.DataRange.Cells(1, 1).Column - 2))
    Else
        'here we shift back from the datarange to the 2nd column of the pivottable
        Set r = .DataRange.Offset(0, -(.DataRange.Cells(1, 1).Column - 2))
    End If
End With

'delete as necessary
r.Select

'obtain the string of cell values from the range
For i = 1 To r.Rows.Count
    str = str & " " & r.Cells(i, 1)
Next i
str = Trim(str)
MsgBox str

End Sub