如何用vba操作切片器?

在excel中可以为数据透视表、智能表格添加切片器。

切片器的作用是用于筛选数据。

在vba中如果要为数据透视表、智能表格添加切片器,可以先录制宏,录制的宏代码如下所示:

Sub 宏1()
'为数据透视表添加切片器
    ActiveWorkbook.SlicerCaches.Add2(ActiveSheet.PivotTables("第一个透视表"), "姓名"). _
        Slicers.Add ActiveSheet, , "姓名 1", "姓名", 154.5, 381, 144, 187.5
    ActiveWorkbook.SlicerCaches.Add2(ActiveSheet.PivotTables("第一个透视表"), "店名"). _
        Slicers.Add ActiveSheet, , "店名", "店名", 192, 418.5, 144, 187.5
End Sub
Sub 宏2()
'为智能表格添加切片器
    ActiveWorkbook.SlicerCaches.Add2(ActiveSheet.ListObjects("表6"), "姓名").Slicers. _
        Add ActiveSheet, , "姓名 2", "姓名", 154.5, 381, 144, 187.5
    ActiveWorkbook.SlicerCaches.Add2(ActiveSheet.ListObjects("表6"), "店名").Slicers. _
        Add ActiveSheet, , "店名 1", "店名", 192, 418.5, 144, 187.5
    ActiveSheet.Shapes.Range(Array("店名 1")).Select
End Sub

从录制的宏中可以看出,要用vba添加切片器,首先要用Workbook对象的SlicerCaches的切片器缓存集合对象的Add方法添加SlicerCache切片器缓存对象。然后用SlicerCache切片器缓存对象的Slicers切片器集合对象的Add方法添加Slicer切片器对象。

经过上述的分析,可以将代码修改为如下的形式:

Sub QQ1722187970()
    Dim oPC As PivotCache
    Dim oPT As PivotTable
    Dim oSC As SlicerCache
    Dim oSlicer As Slicer
    Dim oSP As Shape
    Dim oWB As Workbook
    Dim oWK As Worksheet
    Dim oWKR As Worksheet
    Dim oPF As PivotField
    Dim oRng As Range
    Set oWK = Excel.ActiveSheet
    With oWK
        iCount = .PivotTables.Count
        If iCount = 0 Then
            MsgBox "当前工作表没有数据透视表"
        Else
            Set oPT = .PivotTables(1)
            With oPT
            For Each oPF In .PivotFields
                With oPF
                    '判断属于哪种字段,是行字段,列字段,数值字段,筛选字段,还是其它
                    sType = .Orientation
                End With
            Next
            End With
            Set oWB = Excel.ThisWorkbook
            With oWB
                '删除所有切片器缓存以及切片器
                For Each oSC In .SlicerCaches
                    With oSC
                        .Delete
                    End With
                Next
                '用于存放切片器的工作表
                Set oWKR = .Worksheets("图表")
                '添加一个切片器缓存对象
                Set oSC = .SlicerCaches.Add2(oPT, "姓名")
                '添加一个切片器
                With oSC
                    '直接用命名参数的方式无效
                    'Set oSlicer = .Slicers.Add(SlicerDestination:=oWKR, Top:=oWKR.Range("a1").Top, Left:=oWKR.Range("a1").Left, Width:=oWKR.Range("a1:C1").Width, Height:=oWKR.Range("A1:A10").Height)
                    Set oSlicer = .Slicers.Add(oWKR, , , , oWKR.Range("a1").Top, oWKR.Range("a1").Left, oWKR.Range("a1:C1").Width, oWKR.Range("A1:A15").Height)
                End With
                '添加一个切片器缓存对象
                Set oSC = .SlicerCaches.Add2(oPT, "大指标")
                '添加一个切片器
                With oSC
                    Set oSlicer = .Slicers.Add(oWKR, , , , oWKR.Range("a16").Top, oWKR.Range("a16").Left, oWKR.Range("a1:C1").Width, oWKR.Range("A1:A15").Height)
                End With
            End With
        End If
    End With
End Sub
       

发表评论