简体   繁体   中英

VBA to AutoFilter Dataset Based on Slicer Selections

I have a series of slicers controlling a number of pivot tables which in turn generate some pie charts. From the slicer items selected I would like to autofilter the underlying dataset to summarise the information used to generate the pies. So far I have managed to generate the following code which I admit I have gleaned from another post here: AutoFilter Criteria Using Array (Error) - Too Large String? The code below will AutoFilter the dataset but only using the last item selected in the slicer and not any other selections, ie if all the items of the slicer are selected the AutoFilter only filters using the last item and not the full series. It appears the array element is not working as expected. Any assistance is gratefully accepted. Thank you.

Sub FilterData()
Dim sArr() As String
Dim sCache As SlicerCache
Dim wb As Workbook
Set wb = ThisWorkbook
Set sCache = wb.SlicerCaches("Slicer_Unit")
   For Each sItem In ActiveWorkbook.SlicerCaches(sCache.Name).SlicerItems
        If sItem.Selected = True Then
            ReDim Preserve sArr(0 To sCount)
            sArr(sCount) = sItem.Name
            sCount = sCount + 1
        End If
    Next sItem
 Sheets("Sheet1").Activate
ActiveSheet.Range("$A$1:$Z$50000").AutoFilter Field:=1, Criteria1:=sArr()
ReDim sArr(0 To 0)
End Sub

You need to specify what type of criteria you're providing using the Operator parameter. Change your line

ActiveSheet.Range("$A$1:$Z$50000").AutoFilter _
  Field:=1, _
  Criteria1:=sArr()

to

ActiveSheet.Range("$A$1:$Z$50000").AutoFilter _
  Field:=1, _
  Criteria1:=sArr(), _
  Operator:=xlFilterValues

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