在数据透视表中选择最后3个值(周),但在VBA中没有“空白”

时间:2018-10-28 20:31:08

标签: excel vba excel-vba pivot-table

我有一个包含多个数据透视表的报告。

我在以下数据透视表中找到了下面的宏,该宏可以选择所需的星期数(在我的情况下,我总是需要选择过去3周)。它确实选择了最后3个值,但是问题是,它也选择了“空白”字段。

代码如下:

Sub ShowLastXWeeks()
Dim pi As PivotItem
Dim lLoop As Long
Dim pt As PivotTable
Dim lCount As Long
Dim lWeeks As Long

On Error Resume Next
lWeeks = 3
If lWeeks = 0 Then Exit Sub

Application.ScreenUpdating = False
Set pt = ActiveSheet.PivotTables("PivotTable1")

        For Each pi In pt.PivotFields("Week").PivotItems
            pi.Visible = False
        Next pi


    With pt.PivotFields("Week")
        For lLoop = .PivotItems.Count To 1 Step -1
            .PivotItems(lLoop).Visible = True
            lCount = lCount + 1
            If lCount = lWeeks Then Exit For
        Next lLoop
    End With

On Error GoTo 0
Application.ScreenUpdating = True
End Sub

我的数据透视表如下:

enter image description here

enter image description here

我试图摆脱“空白”价值,但没有成功。

如何修改上面的脚本以省略“空白”字段,而仅选择最近3周?

谢谢。

1 个答案:

答案 0 :(得分:0)

我已经找到了解决自己问题的方法,所以希望我能帮助其他遇到相同问题的人。通过将以下内容添加到我的代码中,我摆脱了“空白”值:

Set pf = pt.PivotFields("Week")
With pf
On Error Resume Next
    .PivotItems("(blank)").Visible = False
On Error GoTo 0
End With

整个代码如下:

Sub ShowLastXWeeks()
Dim pi As PivotItem
Dim lLoop As Long
Dim pt As PivotTable
Dim lCount As Long
Dim lWeeks As Long

On Error Resume Next
lWeeks = 4
If lWeeks = 0 Then Exit Sub

Application.ScreenUpdating = False
Set pt = ActiveSheet.PivotTables("PivotTable1")

    For Each pi In pt.PivotFields("Week").PivotItems
        pi.Visible = False
    Next pi


With pt.PivotFields("Week")
    For lLoop = .PivotItems.Count To 1 Step -1
        .PivotItems(lLoop).Visible = True
        lCount = lCount + 1
        If lCount = lWeeks Then Exit For
    Next lLoop
End With

On Error GoTo 0

Set pf = pt.PivotFields("Week")
With pf
On Error Resume Next
    .PivotItems("(blank)").Visible = False
On Error GoTo 0
End With

Application.ScreenUpdating = True

End Sub

谢谢