Vba 运行错误438以创建数据透视表
我正试图创建一个宏,以便根据数据的一致位置创建透视表。然而,我正在努力克服这个最初的挑战。我一直遵循创建透视宏的指南,但错误438始终会结束宏。代码似乎应该可以工作,但我不明白为什么不能Vba 运行错误438以创建数据透视表,vba,excel,Vba,Excel,我正试图创建一个宏,以便根据数据的一致位置创建透视表。然而,我正在努力克服这个最初的挑战。我一直遵循创建透视宏的指南,但错误438始终会结束宏。代码似乎应该可以工作,但我不明白为什么不能 Sub StockAdjustmentPivot() Dim myFirstRow As Long Dim myLastRow As Long Dim myFirstColumn As Long Dim myLastColumn As Long Set sht = ActiveSheet Dim mySo
Sub StockAdjustmentPivot()
Dim myFirstRow As Long
Dim myLastRow As Long
Dim myFirstColumn As Long
Dim myLastColumn As Long
Set sht = ActiveSheet
Dim mySourceData As String
Dim myDestinationRange As String
Dim myPivotTable As PivotTable
myDestinationRange = sht.Range("T5").Address(ReferenceStyle:=xlR1C1)
myFirstRow = 1
myLastRow = sht.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
myFirstColumn = 1
myLastColumn = 11
With sht.Cells
mySourceData = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)).Address(ReferenceStyle:=xlR1C1)
End With
Set myPivotTable = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="STOCK ADJUSTMENTS REPORT!" & mySourceData).CreatePivotTables(TableDestination:="STOCK ADJUSTMENTS REPORT!" & myDestinationRange, DefaultVersion:="PivotTable1")
End Sub
引发错误的行如下所示:
Set myPivotTable = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="STOCK ADJUSTMENTS REPORT!" & mySourceData).CreatePivotTables(TableDestination:="STOCK ADJUSTMENTS REPORT!" & myDestinationRange, DefaultVersion:="PivotTable1")
在继续介绍透视表的细节之前,我正在尝试解决这个问题
谢谢
编辑
我已根据指导意见将代码拆分为更易于管理的大小:
Dim cache As PivotCache
Set cache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="STOCK ADJUSTMENTS REPORT!" & mySourceData)
Set myPivotTable = cache.CreatePivotTable(TableDestination = "STOCK ADJUSTMENTS REPORT!" & myDestinationRange, TableName:="PivotTable1")
但是,我认为没有定义缓存变量。运行此操作会出现以下错误:
运行时错误5:过程调用或参数无效。TL;医生:你打字有误。将
CreatePivotTable
更改为CreatePivotTable
你有一条指令做了太多的事情: 这就是访问
ActiveWorkbook
的pivot caches集合,使用它创建一个新的pivot缓存,同时使用它创建一个pivot表
Excel aPivotCache
没有CreatePivotTables
成员-因此,对象不支持此属性或方法
将其拆分,并使用正确声明的变量
Dim cache As PivotCache
Set cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="STOCK ADJUSTMENTS REPORT!" & mySourceData)
如果这样做有效,那么您可以使用它来创建透视表——如果它不起作用,至少现在您知道哪个部分失败了(您在单个指令中插入的内容越多,该指令就越难调试):
请注意,当您在
缓存之后键入
点时,VBE会提供一个就地下拉列表(“IntelliSense”):倾听编辑器告诉您本可以避免此键入错误的内容。错误描述是什么?错误描述是“对象不支持此属性或方法”.问题可能与给出错误的行中引用的一个或两个变量的值有关。它们各自的价值是什么?我相信这些价值都很好,它们都生成了正确的列/行。谢谢,采纳了您的建议。然而,新的问题出现了。。。(参见编辑)。这不是免费的调试服务,而是问答。这是关于错误438的问答,这是解决错误438的问答。请避免让你的问题变得复杂。如果您有新错误,并且无法在线找到示例或参考,请随时提出新问题。@Elsybelsy也就是说,您可能需要验证myourcedata
的值(假设问题与缓存
分配有关),和/或包括此[和任何其他相关的]在新帖子中重现问题的信息-请参阅。
Dim cache As PivotCache
Set cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="STOCK ADJUSTMENTS REPORT!" & mySourceData)
Dim pivot As PivotTable
Set pivot = cache.CreatePivotTable(TableDestination:="STOCK ADJUSTMENTS REPORT!" & myDestinationRange, DefaultVersion:="PivotTable1")