将项目列表设置为多个数据透视表

时间:2016-08-17 10:46:26

标签: vba excel-vba pivot-table olap excel

尝试根据我在工作簿中众多数据透视表中的一个中所做的更改,将相同的项目列表设置为多个OLAP数据透视表。

录制的宏是(这也会删除旧的选择):

Sub GetPivotFilter()

ActiveSheet.PivotTables("Pivottabell4").PivotFields( _
    "[DimCampaign].[Campaigns].[Campaign]").VisibleItemsList = Array( _
    "[DimCampaign].[Campaigns].[Campaign].&[106679]", _ 'generated after i select campaing
    "[DimCampaign].[Campaigns].[Campaign].&[106680]", _'generated after i select campaing

    "[DimCampaign].[Campaigns].[Campaign].&[107049]")'generated after i select campaing


End Sub

1 如何在第一个数据透视中提取我所做的更改(在进行更改之前我不知道数字)?

2 如何才能将其应用于可以添加广告系列选项的数据透视表?

我目前的解决方案看起来很混乱,但有效:

Sub SetPivotFilter()

ActiveSheet.PivotTables("Pivottabell4").PivotFields( _
"[DimCampaign].[Campaigns].[Campaign]").VisibleItemsList = Array( _
"[DimCampaign].[Campaigns].[Campaign].&[106679]", _     
"[DimCampaign].[Campaigns].[Campaign].&[106680]", _    
"[DimCampaign].[Campaigns].[Campaign].&[107049]")
ActiveSheet.PivotTables("Pivottabell18").PivotFields( _
"[DimCampaign].[Campaigns].[Campaign]").VisibleItemsList = Array( _
"[DimCampaign].[Campaigns].[Campaign].&[106679]", _     
"[DimCampaign].[Campaigns].[Campaign].&[106680]", _    
"[DimCampaign].[Campaigns].[Campaign].&[107049]")
'and so on
End Sub 

非常感谢所有帮助

1 个答案:

答案 0 :(得分:0)

以下代码遍历所有数据透视表名称为pvtTblNameArr(数组),在工作表名称中为" SheetPivot " (根据您的工作表名称进行修改)。

Option Explicit

Sub GetPivotFilter()

Dim PvtTbl              As PivotTable
Dim pvtitem             As PivotItem
Dim pvtFld              As PivotField
Dim pvtTblNameArr()     As Variant
Dim i                   As Integer

' modify this array to all PivotTable names you need to modify (in the same sheet)
pvtTblNameArr() = Array("Pivottabell4", "Pivottabell8")

' loop though Pivot Table Names
For i = LBound(pvtTblNameArr) To UBound(pvtTblNameArr)

    ' change "SheetPivot" to your sheet name
    Set PvtTbl = ThisWorkbook.Sheets("SheetPivot").PivotTables(pvtTblNameArr(i))

    ' set Pivot field variable to "Campaign"
    Set pvtFld = PvtTbl.PivotFields("Campaign")

    ' lop through all Pivot Items in "Campaign" Pivot Field
    For Each pvtitem In pvtFld.PivotItems

        Select Case pvtitem.Name
            Case 106679, 106680, 107049
                pvtitem.Visible = True

            Case Else
                pvtitem.Visible = False

        End Select

    Next pvtitem

Next i

End Sub