2014-01-27 125 views
0

嗨,我完全是VBA的新手。目前我正在学习如何使用vba创建数据透视表和图表。但是我在调​​试我的代码后面临着Error 91问题,如下所示。 我试图计算在某个特定时间发生failpartid的次数,然后绘制数据透视表以显示计数编号。谢谢!VBA运行时错误91对象变量或块变量未设置

P.S:所以我再次编辑和检查我的代码,但在调试过程中发现“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 
+2

在你所拥有的线这个错误? –

+0

嘿,我刚刚加了一行:With .PivotFields(“FailPartId”) – Solomon

+0

在'With PT'之前加上这行'MsgBox PT Is Nothing'。你会得到什么? –

回答

0

如果你已经把Option Explicit在顶部和调试 - >编译的VBAProject,你会自己解决问题。

替换所有PTCachesPTCache,然后更改行

Dim PTCache As PivotCachesDim PTCache As PivotCache

此外可能成为另一个问题。 TableName:=”PivotTable1”是不一样的TableName:="PivotTable1"

enter image description here

+0

嘿谢谢指出!我尝试过但同样的问题再次发生。是否有可能我设置的数据范围错误,那么代码将无法创建PivotCache? – Solomon

+0

你可以通过在Sub中选择一行来进入宏,请按F8并逐行通过代码?您应该以这种方式更容易地发现错误,因为您可以实时更改变量。 – PatricK

相关问题