Excel VBA数据透视项错误424
我正在处理下面的代码来生成数据透视表。 For Each pivot_item In PvtTb1.PivotFields("Period").PivotItems
这里的For Each pivot_item In PvtTb1.PivotFields("Period").PivotItems
有一个424的错误,这是“需要对象”。
但是我不知道我错过了什么对象。 代码运行良好,没有被标记的部分。
我能解决这个问题吗?
Dim PvtTbl As PivotTable Dim wsData As Worksheet Dim rngData As Range Dim PvtTblCache As PivotCache Dim wsPvtTbl As Worksheet Dim pvtFld As PivotField Set wsData = Worksheets("Verify") Set wsPvtTbl = Worksheets("Summary") wsPvtTbl.Cells.Clear wsPvtTbl.Cells.ColumnWidth = 10 For Each PvtTbl In wsPvtTbl.PivotTables If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then PvtTbl.TableRange2.Clear End If Next PvtTbl Set PvtTblCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ SourceData:="Verify") PvtTblCache.CreatePivotTable TableDestination:=wsPvtTbl.Range("B19"), _ TableName:="PivotTable1" Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1") PvtTbl.ManualUpdate = True 'add row, column and page (report filter) fields: Set pvtFld = PvtTbl.PivotFields("Period") pvtFld.Orientation = xlPageField With wsPvtTbl.PivotTables("PivotTable1").PivotFields("Period") On Error Resume Next .PivotItems("N").Visible = False .PivotItems("Y").Visible = True On Error GoTo 0 End With Dim pivot_item As PivotItem Set pvtFld = PvtTbl.PivotFields("Group") pvtFld.Orientation = xlRowField Set pvtFld = PvtTbl.PivotFields("Name") pvtFld.Orientation = xlRowField pvtFld.Position = 2 For Each pivot_item In PvtTb1.PivotFields("Period").PivotItems If pivot_item.Name = "Y" Then Set pvtFld = PvtTb1.PivotFields("PROCESS_DATE") pvtFld.Orientation = xlColumnField With PvtTbl.PivotFields("NO_REC") .Orientation = xlDataField .Function = xlSum .NumberFormat = "#,##0" .Position = 1 End With End If Next pivot_item
在PvtTb1
,最后有“1”(一个数字),应该是“l”(一个字母)。
既然你已经用这行Set
了PvtTbl
对象Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1")
,你可以简化你的生活,并避免像你这里(混合PvtTbl
和PvtTb1
),通过使用With
statemnet像今后的错误,像在下面的较短版本(和“更清洁”)代码中。
' modify the Pivot-Table properties, afeter you set it With PvtTbl .ManualUpdate = True 'add row, column and page (report filter) fields: With .PivotFields("Period") .Orientation = xlPageField On Error Resume Next .PivotItems("N").Visible = False .PivotItems("Y").Visible = True On Error GoTo 0 End With Dim pivot_item As PivotItem .PivotFields("Group").Orientation = xlRowField With .PivotFields("Name") .Orientation = xlRowField .Position = 2 End With For Each pivot_item In .PivotFields("Period").PivotItems If pivot_item.Name = "Y" Then .PivotFields("PROCESS_DATE").Orientation = xlColumnField With .PivotFields("NO_REC") .Orientation = xlDataField .Function = xlSum .NumberFormat = "#,##0" .Position = 1 End With End If Next pivot_item End With