简体   繁体   English

Excel 360 VBA 更改数据透视表过滤器

[英]Excel 360 VBA to change pivot table filter

I am trying to change the filter on a pivot table that was set up using the "Add this data to the Data Model" functionality using VBA which would read the selection of a list box containing the items to filter on.我正在尝试使用 VBA 更改使用“将此数据添加到数据模型”功能设置的数据透视表上的过滤器,该功能将读取包含要过滤的项目的列表框的选择。 I started by recording a macro to see what would happen and was given this:我首先录制了一个宏,看看会发生什么,然后得到了这个:

ActiveSheet.PivotTables("Pivottable1").PivotFields("[Range 1 1].[Quarter].[Quarter]").VisibleItemsList = _
    Array("[Range 1 1].[Quarter].&[1Q20]", "[Range 1 1].[Quarter].&[3Q20]")

My problem is to set up the array dynamically which could contain any number of items.我的问题是动态设置可以包含任意数量项目的数组。 I need to do something like the below but appending to the array each time which this doesn't do:我需要做类似下面的事情,但每次都附加到数组中,这不会:

For x = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(x) = True Then
       myArray = Array("[Range 1 1].[Quarter].&[" & ListBox1.List(x) & "]")
    End If
Next x

ActiveSheet.PivotTables("Pivottable1").PivotFields("[Range 1 1].[Quarter].[Quarter]").VisibleItemsList = myArray

I tested other ways which didn't work like using:我测试了其他不起作用的方法:

' This didn't work:
Set myArray = CreateObject("System.Collections.ArrayList")
myArray.Add "[Range 1 1].[Quarter].&[1Q20]"

' This method didn't work either
Dim myArray(2) As Variant
myArray2(0) = "1Q20"
myArray2(1) = "2Q20"

I need to replace Array("[Range 1 1].[Quarter].&[1Q20]", "[Range 1 1].[Quarter].&[3Q20]") with something I can set up dynamically.我需要用我可以动态设置的东西替换Array("[Range 1 1].[Quarter].&[1Q20]", "[Range 1 1].[Quarter].&[3Q20]") Any ideas on how I can do this?关于我如何做到这一点的任何想法?

Not sure what you need, but try something like this:不确定你需要什么,但试试这样的:

Dim myArray() As String,k as integer
ReDim myArray(ListBox1.ListCount-1)
k = -1
For x = 0 To ListBox1.ListCount - 1

    If ListBox1.Selected(x) = True Then
    k = k + 1
       myArray(k) = "[Range 1 1].[Quarter].&[" & ListBox1.List(x) & "]"
    End If
Next x
ReDim Preserve myArray(k)

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

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