[英]Run time error '1004' VBA to create pivot table
我正在研究一個宏來為動態命名范圍“DATA”創建一個數據透視表。 我得到一個“運行時錯誤'1004'方法'范圍'對象'_Global'失敗。從我在其他帖子上看到的可能是因為我沒有引用特定的表格?我怎么能糾正這個?
With ActiveWorkbook.Names("DATA")
.Name = "DATA"
.RefersToR1C1 = _
"=OFFSET('Closed Cases'!R1C2,0,0,COUNTA('Closed Cases'!C6),25)"
.Comment = ""
End With
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Range("DATA"), Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:= _
"'External Analytics!'R1C15", TableName:="PivotTable3", DefaultVersion:= _
xlPivotTableVersion14
Sheets("External Analytics").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Resolver")
.Orientation = xlRowField
.Position = 1
End With
假設形成你的帖子,命名范圍“DATA”被正確定義,下面的代碼將根據名為Range的“DATA”中的數據以及你想要的帖子創建PivotTable
。
Option Explicit
Sub DynamicCreatePivot()
Dim wsSheet As Worksheet
Dim PvtTbl As PivotTable
Dim PTCache As PivotCache
' set Pivot destination sheet
Set wsSheet = ThisWorkbook.Sheets("External Analytics")
' set Pivot Cache to the data in "DATA" named range
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, "DATA")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = wsSheet.PivotTables("PivotTable3") ' check if "PivotTable3" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' if Pivot Table is not created
' create a new Pivot Table in "External Analytics" sheet, start from Cell O1 (R1C15)
Set PvtTbl = wsSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=wsSheet.Range("O1"), TableName:="PivotTable3")
'Create the headings and row and column orientation
With PvtTbl.PivotFields("Resolver")
.Orientation = xlRowField
.Position = 1
End With
Else ' Pivot Table already created >> in precious code runs
' just refresh the Pivot cache with the updated Range (named range "DATA")
PvtTbl.ChangePivotCache PTCache
PvtTbl.RefreshTable
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.