简体   繁体   English

根据用户定义范围中的值筛选数​​据透视表

[英]Filter a Pivot table based on values from a user defined range

I'm trying to set up a macro to filter a pivot table based on a user defined range. 我正在尝试建立一个宏,以根据用户定义的范围过滤数据透视表。

So far all I have is the prompt to get the range. 到目前为止,我所能得到的只是提示。 Unfortunately, I have no idea how to take the values from the range and apply it to the filter. 不幸的是,我不知道如何从范围中获取值并将其应用于过滤器。 Thanks for your help! 谢谢你的帮助!

Sub foreachloop()

  Dim wbmodel As Excel.Workbook
Set wbmodel = ActiveWorkbook

Dim rng As Range
Dim Filter As String




  With wbmodel.Sheets("Pivot_model").PivotTables("Modelpivot")

    .ClearAllFilters

     Set rng = Application.InputBox("select Range", "Inputs", Type:=8)
     Filter = Application.InputBox("select Filter", "Inputs", Type:=8)

     MsgBox rng.Address
     MsgBox Filter


    For Each PivotItem In .PivotFields(Filter).PivotItems
    Select Case PivotItem.Name
        Case rng
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem


  End With

  End Sub

Ok. 好。 so I made some (slight) updates. 所以我做了一些(轻微)更新。 I made my first "For Each" loop. 我做了我的第一个“ For Each”循环。 Now, I know I will need to do a similar "for each" loop to apply the filter. 现在,我知道我需要做一个类似的“ for each”循环来应用过滤器。 I've been battling with the code for a few hours and I am unsure where to go next. 我已经与代码争执了几个小时,但我不确定下一步该怎么做。

Try this Filter Excel pivot table using VBA 尝试使用VBA筛选Excel数据透视表

You have to cycle through your range and make the pivot item visible, everything else hidden. 您必须遍历范围,并使枢纽项目可见,其他所有项目都隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM