以下表现得非常奇怪
它的目的是让切片器只包含指定的项目(在本例中为“Smith”),其他所有名称都未选中。
大部分时间它都有效,但有时会选择多个项目。
以下是什么问题以及如何实现所需的行为?
Sub myRoutine()
unselectAllBut "Slicer_InitialAcc_Surname", "me"
End Sub
Public Sub unselectAllBut(slicerName As String, newSelection As String)
Dim si As Object
For Each si In ActiveWorkbook.SlicerCaches(slicerName).SlicerItems
si.Selected = (si.Caption = newSelection)
Next si
End Sub
第二次尝试无效:
Public Sub unselectAllBut(slicerName As String, newSelection As String)
Dim i As Integer
With ActiveWorkbook.SlicerCaches(slicerName)
For i = 1 To .SlicerItems.Count
.SlicerItems(i).Selected = (.SlicerItems(i).Caption = newSelection)
Next i
End With
End Sub
可能数据导致问题。它看起来如下:
编辑
以下似乎有效。我先选择所有看起来像是过度杀戮的物品:
Public Sub unselectAllBut(slicerName As String, newSelection As String)
Dim i As Integer
With ActiveWorkbook.SlicerCaches(slicerName)
For i = 1 To .SlicerItems.Count
.SlicerItems(i).Selected = True
Next i
For i = 1 To .SlicerItems.Count
.SlicerItems(i).Selected = (.SlicerItems(i).Caption = newSelection)
Next i
End With
End Sub
答案 0 :(得分:7)
更快一点:
Public Sub unselectAllBut(slicerName As String, newSelection As String)
Dim i As Integer
With ActiveWorkbook.SlicerCaches(slicerName)
For i = 1 To .SlicerItems.Count
If .SlicerItems(i).Caption = newSelection Then .SlicerItems(i).Selected = True: Exit For
Next i
For i = 1 To .SlicerItems.Count
If .SlicerItems(i).Selected And .SlicerItems(i).Caption <> newSelection Then .SlicerItems(i).Selected = False
Next i
End With
End Sub