比较数据透视表项值时出现运行时1004错误

时间:2015-12-22 16:19:14

标签: excel-vba excel-2013 vba excel

我目前正在处理一组代码,以将数据透视表过滤器设置为特定日期范围。在下面的代码中,日期范围是2015年7月12日至2015年12月22日。在数据中只有12 / 7,8,11,18日期存在。代码将正确标记文件管理器中的那些项目,在12/7之前按照预期省略和日期,但不知何故它会在12/21/2015日期中提取,然后在Bolded代码行中给出运行时错误。我的数据中没有12/21/2015。它也说pi.visible应该是假的,我认为这是错误发生的地方,因为没有12/21/2015它标记为可见或不可见。有什么建议吗?

Dim ws As Worksheet, pt As PivotTable, pf As PivotField, pi As PivotItem
Dim dCurrentDate As Date, dPastDate As Date

dCurrentDate = Date
dPastDate = Date - 15

Set ws = Sheets("Sheet2")
Set pt = ws.PivotTables("PivotTable1")
Set pf = pt.PivotFields("Date")

With pf
   .ClearAllFilters
   For Each pi In pf.PivotItems
   If pi.Value = "(blank)" Then
   Else
        If pi.Value <= dCurrentDate And pi.Value >= dPastDate Then
             **pi.Visible = True**
        Else
             pi.Visible = False
        End If
    End If
   Next
End With

1 个答案:

答案 0 :(得分:0)

代码不需要任何特定日期,它会检查范围。我没有收到错误,但可以简化,无需检查空白。

Dim ws As Worksheet, pt As PivotTable, pf As PivotField, pi As PivotItem
Dim dCurrentDate As Date, dPastDate As Date

    dCurrentDate = Date
    dPastDate = Date - 15

    Set ws = Sheets("Sheet2")
    Set pt = ws.PivotTables("PivotTable1")
    Set pf = pt.PivotFields("Date")

    With pf
       .ClearAllFilters
       For Each pi In pf.PivotItems

            pi.Visible = Trim(pi.Value) <= dCurrentDate And Trim(pi.Value) >= dPastDate
       Next
    End With