【问题标题】:Iterating Pivot Table迭代数据透视表
【发布时间】:2018-03-26 18:05:56
【问题描述】:

我的代码可以遍历我的数据透视表中的每个 PivotItem。我在下面显示的代码是一种更加手动的方法。我的循环将 PivotItem 保存在数据透视表中显示的内容之外,因为数据透视表上有一个过滤器来限制事物。因此,假设我使用.PivotItems("BMR"),并且代码工作正常,因为在数据透视表中显示了 BMR PivotItems。但是,如果我执行.PivotItems("EHFG"),它将出错,因为它不在数据透视表中,因为它正在被过滤掉。

如何调整我的代码,使其不会在不存在的数据透视项上中断?如果 With 语句不存在,也许可以跳过它?

Option Explicit
Sub test()

    Dim PvtTbl As PivotTable
    Dim columnsDifference As Long
    Dim PvtFld As PivotField

    Set PvtTbl = Sheets("NIR Pivot").PivotTables("NIR_Pivot")
    Set PvtFld = PvtTbl.PivotFields("Prod. Code")

    PvtFld.PivotItems("EHFG").ShowDetail = True 'Show pivot item


    columnsDifference = PvtTbl.TableRange2.Columns.Count - PvtTbl.DataBodyRange.Columns.Count
    With PvtTbl.PivotFields("Prod. Code").PivotItems("EHFG").DataRange **ERRORS HERE
   '     Debug.Print .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Address
        .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Select
    End With

End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    试试下面修改后的For Each循环代码:

    Dim Pvtitm As PivotItem ' define pivot-item object
    
    ' loop thorugh all Pivot-items in Pivot Field "Prod. Code"
    For Each Pvtitm In PvtFld.PivotItems
        ' check if current Pivot item is filtered out
        If Pvtitm.Visible = True Then
            With Pvtitm.DataRange
                'Debug.Print .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Address
                .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Select
            End With
        Else
            MsgBox "Pivot-Item " & Pvtitm.Name & " is filtered out", vbInformation
        End If
    
    Next Pvtitm
    

    注意:不知道为什么需要Select Range ?

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 2015-06-25
      相关资源
      最近更新 更多