【发布时间】:2020-01-29 10:36:54
【问题描述】:
我有一个包含大约 120 个选项卡的工作簿,每个选项卡都包含一个或两个数据透视表。
数据透视表每月更新和刷新。
我正在努力折叠所有上一年的数据。
此代码有效,但我需要为之前的每一年更新并重新运行它:
Dim ws As Worksheet
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1" & "*" Or ws.Name Like "2" & "*" Or ws.Name Like "3" & "*" Then
ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems("2015"). _
ShowDetail = False
On Error Resume Next
ws.PivotTables("PivotTable2").PivotFields("Years").PivotItems("2015"). _
ShowDetail = False
End If
Next ws
End Sub
我更喜欢可以折叠所有前一年数据的代码。
我尝试了以下方法,它产生了一个
运行时错误 438 对象不支持此属性或方法:
Dim ws As Worksheet
Dim datecell As Range
Dim cy As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1" & "*" Or ws.Name Like "2" & "*" Or ws.Name Like "3" & "*" Then
'the following line produces the
' run-time 438 object doesn't support this property or method error
If Year(ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems) < cy Then
PivotItem.ShowDetails = False
End If
End If
Next ws
End Sub
我也尝试了以下方法,它产生了一个
运行时错误 13 类型不匹配:
Dim ws As Worksheet
Dim datecell As Range
Dim cy As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1" & "*" Or ws.Name Like "2" & "*" Or ws.Name Like "3" & "*" Then
For Each PivotItem In ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems
'the following line produces the run-time 13 type mismatch error
If Year(PivotItem) < cy Then
PivotItem.ShowDetails = False
End If
Next PivotItem
End If
Next ws
End Sub
如何更正我的代码?
编辑 1:
下面的代码产生一个
运行时错误 438:对象不支持此属性或方法:
Dim ws As Worksheet
Dim pt As PivotTable
Dim ptItm As PivotItem
Dim datecell As Range
Dim cy As Long
Dim ptItmY As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1" & "*" Or ws.Name Like "2" & "*" Or ws.Name Like "3" & "*" Then
For Each pt In ws.PivotTables
For Each ptItm In pt.PivotFields("Years").PivotItems
ptItmY = Right(ptItm, 4)
If ptItmY < cy Then
'the following line produces
' run-time error 438: Object doesn't support this property or method
ptItm.ShowDetails = False
Else: ptItm.ShowDetails = True
End If
Next ptItm
Next pt
End If
Next ws
End Sub
【问题讨论】:
-
试试“If Year(PivotItem.Value)”。
-
@Qqqqq 试试我下面回答中的代码
-
@Mats Lind .value 不起作用,因为 Excel 添加了小于和大于值,因此并非年份字段中的所有值都采用 2015、2016 等格式。