gpt4 book ai didi

vba - 通过 VBA 遍历切片器并每次选择一个项目

转载 作者:行者123 更新时间:2023-12-04 21:12:43 25 4
gpt4 key购买 nike

我在一个电子表格中有几个切片机。我希望能够通过 VBA 循环其中一个,并一一选择每个选项。
下面的宏对我疲惫的眼睛来说似乎很好,但是当我运行它时它显然不起作用。当我在下面的'BREAKPOINT 标记处添加断点时,第一个项目被选中,但随后宏转到第二个,同时保持第一个被选中,我最终选择了所有项目......

    Sub slicers(slName As String)
Dim slItem As SlicerItem, slDummy As SlicerItem
Dim slBox As SlicerCache
Set slBox = ActiveWorkbook.SlicerCaches(slName)
For Each slItem In slBox .SlicerItems
For Each slDummy In slBox .SlicerItems
slDummy.Selected = (slDummy.Name = slItem.Name)
Next slDummy
Next slItem 'BREAKPOINT
End Sub

Sub test()
Call slicers("A_slicer_name")
End Sub

谢谢你的帮助

编辑:
正如 Scott Holtzman 所指出的,我只需要在选择新项目时清除过滤器 (slBox.ClearManualFilter)。

为什么这是必要的,而 bool 测试在我 debug.print 时可以正常工作?

下面的代码工作正常:
    Sub slicers(slName As String)
Dim slItem As SlicerItem, slDummy As SlicerItem
Dim slBox As SlicerCache
Set slBox = ActiveWorkbook.SlicerCaches(slName)
For Each slItem In slBox .SlicerItems
slBox.ClearManualFilter 'THIS IS THE LINE I NEEDED TO ADD
For Each slDummy In slBox .SlicerItems
slDummy.Selected = (slDummy.Name = slItem.Name)
Next slDummy
Next slItem
End Sub

Sub test()
Call slicers("A_slicer_name")
End Sub

最佳答案

由于我在评论中也链接了你的问题没有被接受的答案(用户从不选择回答或回复我的建议),我也会在这里为你的问题提供解决方案。

Sub slicers(slName As String)

Dim slItem As SlicerItem, slDummy As SlicerItem
Dim slBox As SlicerCache

Set slBox = ActiveWorkbook.SlicerCaches(slName)

'loop through each slicer item
For Each slItem In slBox.SlicerItems

'show all items to start
slBox.ShowAllItems 'or .ClearManualFilter

'test each item against itself
For Each slDummy In slBox.SlicerItems

'if the item equals the item in the first loop, then select it
'otherwise don't show it (thus showing 1 at a time between the nested loops)
If slItem.Name = slDummy.Name Then slDummy.Selected = True Else: slDummy.Selected = False

'more code to process the data (I suspect)

Next slDummy

Next slItem

End Sub

关于vba - 通过 VBA 遍历切片器并每次选择一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com