从VBA函数Excel更新切片器(1004错误)

时间:2016-04-11 19:42:29

标签: excel excel-vba vba

我正在尝试使用VBA代码更改excel文档中的切片器。到目前为止,我已经尝试了几乎所有的东西,我总是得到同样的错误:

Run-time error '1004':

Application-defined or object-defined error

这是我目前的VBA代码。

Sub SelectSlicerValue(ByVal SlicerName As String, ByVal slicerVal As String, ByVal isSelected As Boolean)
    ActiveWorkbook.SlicerCaches(SlicerName).SlicerItems(slicerVal).Selected = isSelected
End Sub

'Selects slicer values to display only data for 17-year old male students
Sub SelectMale17Profile()
    SelectSlicerValue "Slicer_Age1", "17", True
End Sub

我相信我已经在某处读过,我需要在能够动态更改所选过滤器之前启用切片器的读/写属性。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

  

@SiddharthRout - 感谢您的回复!是的,我使用powerpivot连接到我的sql数据库。这是一个问题,还是仍然可以用VBA更改切片器? - TobiasKnudsen 6小时前

如果您的数据透视表从外部源获取数据,则使用SlicerCacheLevels集合循环切片器中的项目并执行您想要的操作。例如

'Selects slicer values to display only data for 17-year old male students
Sub SelectMale17Profile()
    SelectSlicerValue "Slicer_Age1", "17", True
End Sub

Sub SelectSlicerValue(ByVal SlicerName As String, ByVal slicerVal As String, ByVal isSelected As Boolean)
    Dim oSitm As SlicerItem
    Dim oSlvl As SlicerCacheLevel

    For Each oSlvl In ActiveWorkbook.SlicerCaches(SlicerName).SlicerCacheLevels
        For Each oSitm In oSlvl.SlicerItems
            If oSitm.Value = slicerVal Then oSitm.Selected = isSelected
        Next
    Next
End Sub

从不同的角度来看,我认为这是你想要做的事情?我删除了isSelected

'Selects slicer values to display only data for 17-year old male students
Sub SelectMale17Profile()
    SelectSlicerValue "Slicer_Age1", "17", True
End Sub

Sub SelectSlicerValue(ByVal SlicerName As String, ByVal slicerVal As String)
    Dim oSitm As SlicerItem
    Dim oSlvl As SlicerCacheLevel

    For Each oSlvl In ActiveWorkbook.SlicerCaches(SlicerName).SlicerCacheLevels
        For Each oSitm In oSlvl.SlicerItems
            If oSitm.Value = slicerVal Then
                oSitm.Selected = True
            Else
                oSitm.Selected = False
            End If
        Next
    Next
End Sub