[英]Procedure Error when creating a pivot table using VBA
當我運行下面的VBA代碼創建數據透視表時,運行宏時出現“無效的過程或調用參數錯誤”。 錯誤在“ Set PT”區域中。
我已經定義了工作表對象,但我也嘗試調整“表目標”以直接引用工作表,但仍然遇到相同的錯誤。
知道什么可能導致錯誤嗎?
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
構建透視緩存,而是使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.