0
我正在創建一個數據透視表。我有三張工作表,我在工作表CAT_Pivot
中創建數據透視表,並在準備工作表中填寫數據。創建數據透視表時出錯:「應用程序定義的或對象定義的錯誤。」
我能夠實現我的目標,但在執行結束時出現運行時錯誤。運行時錯誤狀態
應用程序定義的或對象定義的錯誤。
要補充說明,如何計算數據透視表中的值?我用.function = xlcount
,我沒有成功。
這裏是我的代碼:
Sub AutoPivot()
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtSht As Worksheet
' set Pivot Cache for Pivot Table
' Your range is static, there are ways to refer to a dynamic range
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Preparation sheet!R1C1:R1048576C8")
' set the Pivot table's sheet
Set PvtSht = Worksheets("CAT_Pivot")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = PvtSht.PivotTables("PivotTable1") ' check if "PivotTable7" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' Pivot table object is nothing >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("A3"), TableName:="PivotTable1")
With PvtTbl
With .PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Category")
.PivotItems("DG-035583").Visible = False
.PivotItems("DG-048917").Visible = False
.PivotItems("DG-Series").Visible = False
.PivotItems("gn").Visible = False
.PivotItems("yl").Visible = False
.PivotItems("(blank)").Visible = False
End With
With .PivotFields("Colour")
.PivotItems("(blank)").Visible = False
End With
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub
謝謝。我會重寫它並嘗試。 – Mikz
@Mikz - 同樣,嘗試構建一個較小的問題模型併發布,如果您仍然體驗它的話。例如,只有幾個'PivotItems'和'PivotFields'。 – Vityata
我試了你的建議,錯誤依然存在。 – Mikz