运行时错误' 1004' VBA创建数据透视表

时间:2016-11-30 15:41:08

标签: excel-vba runtime-error pivot-table vba excel

我正在研究一个宏来为动态命名范围" 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

1 个答案:

答案 0 :(得分:0)

假设形成你的帖子,命名范围" DATA"如果正确定义,下面的代码将根据" 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