嗨,我对VBA全新。目前我正在学习如何使用vba创建数据透视表和图表。但是我在调试我的代码后面临错误91问题,如下所示。我试图计算在某个时间发生的failpartid的数量,然后绘制pivottable以显示计数。谢谢!
P.S:所以我再次编辑并检查了我的代码,但在调试过程中发现“PT没什么”。我一开始有昏暗的PT,有人知道为什么吗?
With .PivotFields("FailPartId") is the line has the error.
Sub Trial1()
Dim PTCache As PivotCaches
Dim PT As PivotTables
Dim PF As PivotFields
Dim FinalCol As Long
FinalCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
'Range("E1:F1").Select
'Range(Selection, Selection.End(xlDown)).Select
Selection.Name = "PivotData"
Application.Goto Reference:="Trial1"
'Create the Cache
Set PTCaches = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="ActiveSheet!A1")
'Create the pivot table
Set PT = PTCaches.CreatePivotTable(TableDestination:=ActiveSheet.Cells(1, FinalCol + 2), TableName:=”PivotTable1”, ReadData:="PivotData")
'Set the Fields
With PT
'Set column field
With .PivotFields("FailPartId")
.Orientation = xlColumnField
.Position = 1
End With
'Set Row field
With .PivotFields("ProductionYM")
.Orientation = xlRowField
.Position = 1
End With
'Set data feild
ActiveSheet.AddDataField.PivotFields ("FailPartId"), "Count of FailPartId", xlCount
End With
End Sub
如果你把Option Explicit
放在顶部并调试 - >编译VBAProject,你将自己解决它。
用PTCaches
替换所有PTCache
,然后更改线
Dim PTCache As PivotCaches
到Dim PTCache As PivotCache
。
”
也可能成为另一个问题。 TableName:=”PivotTable1”
与TableName:="PivotTable1"
不同