使用VBA创建透视表时发生过程错误
当我运行下面的VBA代码来创建透视表时,运行宏时会出现无效过程或调用参数错误。错误在设定的PT区域 我已经定义了工作表对象,但我也尝试调整表目的地以直接引用工作表,但仍然得到相同的错误 知道是什么导致了这个错误吗使用VBA创建透视表时发生过程错误,vba,excel,Vba,Excel,当我运行下面的VBA代码来创建透视表时,运行宏时会出现无效过程或调用参数错误。错误在设定的PT区域 我已经定义了工作表对象,但我也尝试调整表目的地以直接引用工作表,但仍然得到相同的错误 知道是什么导致了这个错误吗 With wsData Dim PTCache As PivotCache Dim PT As PivotTable 'Creates the Cache Set PTCache = ActiveWorkbook.PivotCaches.Create(
With wsData
Dim PTCache As PivotCache
Dim PT As PivotTable
'Creates the Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=.Range("A1").CurrentRegion)
'Creates pivot table
Set PT = wsPivot.PivotTables.Add( _
PivotCache:=PTCache, _
TableDestination:=wsPivot)
'Defines fields
With PT
.PivotFields("Field 1").Orientation = xlRowField
.PivotFields("Field 2").Orientation = xlRowField
.PivotFields("Field 3").Orientation = xlRowField
.AddDataField .PivotFields("Field 4"), "Field 4", xlCount
.TableStyle2 = "PivotStyleMedium2"
End With
End With
我发现了这个问题,并没有从ActiveWorkbook构建pivot缓存,而是使用了ThisWorkbook 运行以下代码时未出错:
With wsData
Dim PTCache As PivotCache
Dim PT As PivotTable
'Creates the Cache
Set PTCache = ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=.Range("A1").CurrentRegion)
'Creates pivot table
Set PT = wsPivot.PivotTables.Add( _
PivotCache:=PTCache, _
TableDestination:=wsPivot)
'Defines fields
With PT
.PivotFields("Field 1").Orientation = xlRowField
.PivotFields("Field 2").Orientation = xlRowField
.PivotFields("Field 3").Orientation = xlRowField
.AddDataField .PivotFields("Field 4"), "Field 4", xlCount
.TableStyle2 = "PivotStyleMedium2"
End With
End With
wsPivot是什么?它是一个工作表对象,类似于“[sheet.xlsm]SheetsPivot”的TableDestination参数需要指定的范围。再见,谢谢。基于这些信息,我将该部分调整为:Set PT=wsPivot.PivotTables.Add PivotCache:=PTCache,TableDestination:=wsPivot.RangeA3,u TableName:=Pivot Table我仍然收到相同的错误:运行时错误“5”:过程调用或参数无效