Excel VBA更新透视字段
我记录了这一点:Excel VBA更新透视字段,excel,vba,pivot-table,Excel,Vba,Pivot Table,我记录了这一点: With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth") .PivotItems("2016-10").Visible = False .PivotItems("2017-11").Visible = True End With 每个月,我都会把这份报告作为一份连续13天的报告来运行。这是本月运行的。我们先减去两个月,再加上一个月。我希望这是有道理
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
.PivotItems("2016-10").Visible = False
.PivotItems("2017-11").Visible = True
End With
每个月,我都会把这份报告作为一份连续13天的报告来运行。这是本月运行的。我们先减去两个月,再加上一个月。我希望这是有道理的。无论如何,虽然这段代码在12月份有效,但每个月都不好用。我还需要指出的是,每年的一月都是不同的
我想到了这个:
Sub Update_Pivots()
Dim thisMonth As Integer
Dim lastMonth As Integer
Dim thisYear As Integer
If Month(Date) = 1 Then
thisYear = Year(Date) - 1
thisMonth = Month(Date) - 1
lastMonth = Month(Date) - 2
Else
thisYear = Year(Date)
thisMonth = Month(Date) - 1
lastMonth = Month(Date) - 2
End If
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
.PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
.PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
.PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
.PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With
End Sub
我收到一个运行时“1004”错误
无法获取PivotField类的PivotItems属性
尽管日期适用于一月,但它们不适用于二月,因为这个月和年份应该是当前的,而上个月和年份应该是前一年
这是我的第一篇文章。我一直在用VBA做很多简单的事情,但现在正因为如此,我被要求做更多的事情
谢谢你的帮助 只需使用
DateAdd
计算正确的月份,然后将其格式设置为“yyyy-mm”
:
Sub Update_Pivots()
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
.PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
.PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
End With
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
.PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
.PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
End With
End Sub