使用VBA循环遍历工作簿切片器名称

时间:2013-12-10 01:28:25

标签: excel vba excel-vba excel-2010

我尝试过谷歌搜索并搜索这个但是却无法得到它。我要做的就是遍历活动工作表上的切片器并删除切片器(如果存在)。

此刻我有6个切片机坐在那里。以前我有

    ActiveSheet.Shapes.Range(Array("Market Segment Name 2", "Line of Business 2" _
    , "Customer Name", "Product Group Name", "Product Type Name", "Product Code") _
    ).Select
    Selection.Delete

但如果我已经删除了切片器,那就不好了。

现在我正在尝试(注意wb在名为“Public”的模块中设置为全局变量)

Option Explicit
Dim sl As Slicer
Dim slName As String

Set wb = ActiveWorkbook

For Each sl In wb.SlicerCaches
    If sl.Name = "Market Segment Name 2" Or _
        sl.Name = "Line of Business 2" Or _
        sl.Name = "Customer Name" Or _
        sl.Name = "Product Group Name" Or _
        sl.Name = "Product Type Name" Or _
        sl.Name = "Product Name" Then
        slName = sl.Name
        ActiveSheet.Shapes.Range(slName).Delete
    End If
Next sl

对我而言似乎应该有效。如果我进入SlicerItem级别,我已经得到了它的工作,但我无法弄清楚如何在切片级别访问它...

任何想法都将不胜感激。谢谢。

如果失败了,我将继续构建数组并删除该方法,但我仍然需要一种方法来测试切片器当前是否存在。

2 个答案:

答案 0 :(得分:5)

我能想到两种方式。

一种是Force方法。这里我们不检查切片器是否存在。我们只是删除它,如果它存在。例如

On Error Resume Next
ActiveSheet.Shapes.Range("Market Segment Name 2").Delete
ActiveSheet.Shapes.Range("Line of Business 2").Delete
'
'~~> And so on
'
On Error GoTo 0

另一种方法是实际检查切片器是否存在然后将其删除。例如

Dim sl As SlicerCache

On Error Resume Next
Set sl = ActiveWorkbook.SlicerCaches("Market Segment Name 2")
On Error GoTo 0

If Not sl Is Nothing Then sl.Delete

'For Each sl In ActiveWorkbook.SlicerCaches
    'Debug.Print sl.Name
'Next

修改

评论后续。

将第一个代码转换为循环。

Sub Sample()
    Dim sSlicers As String
    Dim Myar
    Dim i As Long

    '~~> Slicers you want to delete
    sSlicers = "Market Segment Name 2,Line of Business 2"
    sSlicers = sSlicers & "," & "Customer Name,Product Group Name"
    sSlicers = sSlicers & "," & "Product Type Name,Product Code"

    '~~> Split the names using "," as a delimiter
    '~~> If your slicer names have "," then use a different delimiter
    Myar = Split(sSlicers, ",")

    For i = LBound(Myar) To UBound(Myar)
        On Error Resume Next
        ActiveSheet.Shapes.Range(Myar(i)).Delete
        On Error GoTo 0
    Next i
End Sub

答案 1 :(得分:2)

这是另一个代码,我终于想到要做我原本想要实现的目标。

Sub LoopSlicerNames()

Dim slCaches As SlicerCaches
Dim slCache As SlicerCache

Set slCaches = ThisWorkbook.SlicerCaches

For Each slCache In slCaches

    'MsgBox (slCache.Name & " is used for " & slCache.PivotTables.Item(1).Name)
    If slCache.PivotTables.Item(1).Name = "PTDashboard" Then
        slCache.Delete
        'MsgBox ("Slicer has been deleted")
    End If

    'If slCache.Name = "Slicer_Market_Segment_Name2" Then slCache.Delete

Next slCache

End Sub

与此问题的不同之处在于,我根据工作表上的父透视表来定位切片器,因此我不需要将切片器的确切名称添加到代码中。如果我确实想在代码中添加切片器的名称,我可以切换注释。

再次感谢Siddarth。你让我超越了最初的障碍并提供了很好的解决方案。我认为我最初的问题是认为切片器是slicercache的孩子。现在看来它似乎是sliceerCaches,SlicerCache然后是SlicerItem和'切片器'正如我在原来的问题中所提到的那样,是' SlicerCache'等级...所以我联系的图片让我感到困惑哈哈。