如何加快切片器VBA代码选择

时间:2018-11-19 11:05:47

标签: excel vba excel-vba

希望每个人都很好。

我已经获得了进行切片器选择的代码(第一项):

Sub test()


Dim sc As SlicerCache

Set sc = ActiveWorkbook.SlicerCaches("Slicer_book1")


On Error GoTo errHandler
Application.ScreenUpdating = False
Application.EnableEvents = False

For Each pt In sc.PivotTables
    pt.ManualUpdate = True 
Next pt

    With ActiveWorkbook.SlicerCaches("Slicer_book1")
    .ClearManualFilter
    cnt = .SlicerItems.Count
    If cnt > 1 Then
        For i = 2 To cnt
            .SlicerItems(i).Selected = False
        Next
    End If
End With

For Each pt In sc.PivotTables
    pt.ManualUpdate = False
Next pt

exitHandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub

errHandler:
MsgBox ("Error in updating slicer filters.")
Resume exitHandler

以某种方式,此代码可以工作,但是它确实显示出来。因此,我想知道是否有人对如何适当加快速度有任何建议?

感谢和问候。

1 个答案:

答案 0 :(得分:0)

与切片器相比,我更喜欢使用数据透视表名称。

Sub test()


Dim sc As SlicerCache
Dim SIName As String
Dim pt As PivotTable, PTF As PivotField

Set sc = ActiveWorkbook.SlicerCaches("Slicer_book1")


On Error GoTo errHandler
Application.ScreenUpdating = False
Application.EnableEvents = False

For Each pt In sc.PivotTables
    pt.ManualUpdate = True 
Next pt

    With ActiveWorkbook.SlicerCaches("Slicer_book1")
    '.ClearManualFilter
    cnt = .SlicerItems.Count
    If cnt > 1 Then
        SIName  = .SlicerItems(1).Name
    End If
End With

'Pivot is the sheet name where the pivot table is located
ActiveWorkbook.Worksheets("Pivot").Activate
Set pt = ActiveWorkbook.Worksheets("Pivot").PivotTables("NameOfPivotTable")
'Book is pivot field
Set PTF = pt.PivotFields("Book")
PTF.ClearAllFilters
PTF.CurrentPage = SIName

For Each pt In sc.PivotTables
    pt.ManualUpdate = False
Next pt

exitHandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub

errHandler:
MsgBox ("Error in updating slicer filters.")
Resume exitHandler

End Sub

希望获得帮助