我有一个名为'Slicer_HeaderTitle'的切片器。我只需要能够使用所选元素的值对VBA中的变量进行调暗。我一次只能选择一个元素。
由于我的数据透视表连接到外部数据源,因此我通过VBA动态选择和取消选择切片器中的元素时遇到了很多问题。我不知道这是否与这个确切的示例相关,但此表连接到相同的外部数据源。
我曾经只有一行代码,可以返回这个值,但我现在找到的所有代码都要求你遍历切片器中的每个元素并检查它是否被选中。我希望避免这种情况,因为我一次只有一个选定的元素。
' This is what I'm trying to achieve.
Dim sValue as String
sValue = ActiveWorkbook.SlicerCaches("Slicer_HeaderTitle").VisibleSlicerItems.Value
msgbox(sValue)
'Returns: "Uge 14 - 2016 (3. Apr - 9. Apr)"
现状:
答案 0 :(得分:4)
这就是我所做的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
<dependentAssembly>
<!-- Note: type: The value must be win32 and all in lower case. Required. -->
<!-- Note: version: The value must be win32 and all in lower case. Required. -->
<assemblyIdentity
type="win32"
name="plugins"
version="1.0.0.0"
/>
</dependentAssembly>
</dependency>
</assembly>
感谢Doktor OSwaldo帮助了我很多!
答案 1 :(得分:3)
好的找到错误,我们将退后一步,删除我的功能并尝试循环浏览项目:
Dim sC As SlicerCache
Dim SL As SlicerCacheLevel
Dim sI As SlicerItem
Set sC = ActiveWorkbook.SlicerCaches("Slicer_Dates_Hie")
Set SL = sC.SlicerCacheLevels(1)
For Each sI In SL.SlicerItems
sC.VisibleSlicerItemsList = Array(sI.Name)
Next
答案 2 :(得分:1)
我想投入两分钱。可见的切片器项目集可以通过两个独立的操作缩小:
.Selected
方法。.HasData
方法。请注意,您可能只会看到说Slicer_Products
的两个项目(苹果,香蕉),因为其他一些切片器Slicer_Product_Type
在fruits
上具有活动过滤器。方法sI.Selected
仍会返回苹果,香蕉,胡萝卜等产品的整个清单。
如果要同时设置两个限制,则使两个集合相交。我已经修改了TobiasKnudsen代码(出色的答案!),以返回由于上述两个限制而缩小的项目列表。 If sI.Selected = True And sI.HasData = True Then
是此代码中的关键行。
Option Explicit
Sub TestExample()
Dim MyArr() As Variant
MyArr = ArrayListOfSelectedAndVisibleSlicerItems("Slicer_A")
'now variable MyArr keeps all items in an array
End Sub
Public Function ArrayListOfSelectedAndVisibleSlicerItems(MySlicerName As String) As Variant
'This function returns an array of the limited set of items in Slicer A
'Limitation is due to both:
'(1) direct selection of items by user in slicer A
'(2) selection of items in slicer B which in consequence limits the number of items in slicer A
Dim ShortList() As Variant
Dim i As Integer: i = 0 'for iterate
Dim sC As SlicerCache
Dim sI As SlicerItem 'for iterate
Set sC = ThisWorkbook.Application.ActiveWorkbook.SlicerCaches(MySlicerName)
For Each sI In sC.SlicerItems
If sI.Selected = True And sI.HasData = True Then 'Here is the condition!!!
'Debug.Print sI.Name
ReDim Preserve ShortList(i)
ShortList(i) = sI.Value
i = i + 1
End If
Next sI
ArrayListOfSelectedAndVisibleSlicerItems = ShortList
End Function
答案 3 :(得分:0)
Sub Demo()
Dim i As Integer
With ActiveWorkbook.SlicerCaches("Slicer_Country")
For i = 1 To .SlicerItems.Count
If .SlicerItems(i).Selected Then
Sheets("Pivot Sheet").Range("I" & i) = SlicerSelections & " " & .SlicerItems(i).Value
End If
Next i
End With
End sub