当A1值更改时,在数据透视切片器中选择项目

时间:2019-10-18 04:16:38

标签: excel vba

当我更改“ A1”值时,我试图在数据透视切片器中选择一个项目。
因此,当我将“ A1”值更改为“ ABC”时,代码应在“切片器项目”中查找“ ABC”并选择它。
“ A1”值将与切片器中的项目相同。

这是我的尝试,但似乎不起作用,看起来也不正确:(

Private Sub WorkSheet_Change(ByVal Target As Range)

Dim i As Integer
Dim ws As Worksheet
Set ws = ActiveSheet

If Not Intersect(Target, Range("A1")) Is Nothing Then
    For i = 1 To ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems.Count
        If ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Value = ActiveSheet.Range("A1") Then
           ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = True
        Else
           ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = False
        End If
    Next
End If 
End Sub

谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了可行的方法。
这不是完美的方法,但是可以,但是仍在寻找一种更好的方法来实现。

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim i As Integer
    Dim ws As Worksheet
    Set ws = ActiveSheet

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        ActiveWorkbook.SlicerCaches("Slicer_Test").Slicers(1).SlicerCache.ClearAllFilters
        For i = 1 To ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems.Count
            If ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Value <> ActiveSheet.Range("A1") Then
               ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = False
            End If
        Next
    End If

End Sub