VBA 运行时错误 91 对象变量或未设置块变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21390440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA run time error 91 Object variable or with block variable not set
提问by Solomon
Hi I am totally new to VBA. Currently I am learning how to use vba to create Pivottable and charts. But I am facing the Error 91 problem after debugged my code as below. I am trying to count the number of failpartid occurred at certain time, and then draw the pivottable to show the count number. Thank you!
嗨,我是 VBA 的新手。目前我正在学习如何使用 vba 创建数据透视表和图表。但是在调试我的代码后,我正面临错误 91 问题,如下所示。我试图计算特定时间发生的failpartid的数量,然后绘制数据透视表以显示计数数量。谢谢!
P.S: So I edited and checked my code again, but found out the "PT is nothing" during debugging. I have dim PT at the beginning, does anybody know why?
PS:所以我再次编辑并检查了我的代码,但在调试过程中发现“PT is nothing”。我一开始有暗淡的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
回答by PatricK
If you have put Option Explicit
at the top and to Debug-->Compile VBAProject, you will solve it yourself.
如果您已将其放在Option Explicit
顶部并进行Debug-->Compile VBAProject,您将自己解决。
Replace all PTCaches
with PTCache
and then change the line
全部替换PTCaches
为PTCache
,然后更改行
Dim PTCache As PivotCaches
to Dim PTCache As PivotCache
.
Dim PTCache As PivotCaches
到Dim PTCache As PivotCache
。
Also the ”
may become another issue. TableName:=”PivotTable1”
is not the same as TableName:="PivotTable1"
也”
可能成为另一个问题。TableName:=”PivotTable1”
不一样TableName:="PivotTable1"