简体   繁体   中英

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. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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