专家和专家,
我为数据透视表编写了以下代码,它正在生成pi.Visible错误。
Sub piVisibleMismatch()
Dim lastrow As Long, endrow As Long
Dim Psheet As Worksheet, Dsheet As Worksheet
Dim Pcache As PivotCache, Ptable As PivotTable, Prange As Range
Dim i As Long, j As Long, pi As PivotItem
Dim currep_date As Date
Application.ScreenUpdating = False
currep_date = "31/10/2019"
Worksheets("Summary").UsedRange
Worksheets("PivotTable").Activate
ActiveSheet.Cells.ClearContents
ActiveSheet.Cells.ClearFormats
ActiveSheet.Tab.ColorIndex = xlColorIndexNone
Set Psheet = Worksheets("PivotTable")
Set Dsheet = Worksheets("Summary")
lastrow = Dsheet.Cells(Rows.Count, 1).End(xlUp).Row
Set Prange = Dsheet.Range("A2:O" & lastrow)
On Error Resume Next
Set Pcache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Prange). _
CreatePivotTable(TableDestination:=Psheet.Cells(6, 1), TableName:="Total_Table")
Set Ptable = Pcache.CreatePivotTable(TableDestination:=Psheet.Cells(6, 1), TableName:="Total_Table")
With ActiveSheet.PivotTables("Total_Table").PivotFields("Balance 2")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
End With
With ActiveSheet.PivotTables("Total_Table").PivotFields("Type of Account")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("Total_Table").PivotFields("Collection Date")
.Orientation = xlPageField
.Position = 3
End With
With ActiveSheet.PivotTables("Total_Table").PivotFields("Reporting CCY")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("Total_Table").PivotFields("Type of Account").CurrentPage = "Regular"
With ActiveSheet.PivotTables("Total_Table").PivotFields("Collection Date")
For Each pi In .PivotItems
If CDate(pi.Name) > currep_date + 30 Then
pi.Visible = False
End If
Next pi
End With
On Error GoTo 0
ActiveSheet.PivotTables("Total_Table").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("Total_Table").TableStyle2 = "PivotStyleLight2"
ActiveSheet.UsedRange
ActiveSheet.Range("B:F").Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
ActiveSheet.Cells.Font.Name = "Arial"
ActiveSheet.Cells.Font.Size = 8
ActiveSheet.Range("A:A").ColumnWidth = 35#: ActiveSheet.Range("B:F").ColumnWidth = 15#
ActiveSheet.Range("A1").Select
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
其他2个工作表也有类似的错误,但是调试超过5个小时后,我可以跟踪lastrow不匹配错误。数据透视表的源工作表中的最后一行已更新,该行由调试时无意中包含无关数据的行组成。当我发现数据透视表的数据范围和最后一行的数据范围不同时,我删除了不相关的数据,运行了正确更新了lastrow的宏,然后正确地过滤了日期。
在现有工作表中,源工作表中的日期为日期数据类型,并且currep_date变量也设置为日期数据类型。我比以前更努力地工作,并在许多网站上研究文章以识别错误,但我仍然一无所知。
感谢您的宝贵时间,感谢您分享宝贵的知识,并要求提供任何其他解决方案来过滤日期而不更改日期数据类型。
亲切的问候, Roshan Shakya