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

我想用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 

我相信我已经阅读过某处,我需要启用切片机的读/写属性,才能dynamic更改所选的filter。 我该怎么做呢?

@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 

从另一个angular度来看,我认为这就是你想要做的? 我删除了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