【发布时间】:2018-09-20 18:31:06
【问题描述】:
我需要帮助过滤具有日期范围的数据透视项目。这些项目是 2014 年至 2018 年间格式为 YYYY-MM-DD 的日期。我希望只有过去 12 个月的项目在数据透视表中可见。
我想出的代码首先检查数据透视表下拉列表中的所有项目。然后它应该取消选中所有不在 12 个月范围内的项目。
问题:代码没有过滤任何内容,因此所有项目仍然可见。
Dim pivot As PivotItem
Dim currentMonth As Integer
Dim currentYear As Integer
currentMonth = Month(Date)
currentYear = Year(Date)
ActiveSheet.PivotTables("OEMI").RefreshTable
ActiveSheet.PivotTables("OEMI").PivotFields("Date sent to Coordinator").EnableMultiplePageItems = True
For Each pivot In ActiveSheet.PivotTables("OEMI").PivotFields("Date sent to Coordinator").PivotItems
If Not (Year(pivot) = currentYear And Month(pivot) <= currentMonth) Or _
(Year(pivot) = currentYear - 1 And Month(pivot) > currentMonth) Then
pivot.Visible = False
Else
'Do nothing and stay visible in the drop-down list
End If
Next pivot
编辑********************** 当代码通过 For Each 循环时,我使用监视窗口查看变量的值和类型。看来我的 pivot.visible = true/false 方法存在类型不匹配问题。任何想法可能是什么问题? Watch Window
【问题讨论】:
-
你有没有可能有类似日期的文本?
-
不,数据透视项目采用日期格式。 Year(date) 和 Year(pivot) 返回一个整数。
-
Year仍然适用于看起来像日期的文本。 -
数据透视表从另一个工作簿获取其源数据。我已经验证了源数据中单元格的格式是日期格式 YYYY-MM-DD。
-
可以添加数据的sn-p截图吗?
标签: excel vba filter ms-office pivot-table