Excel VBA:在没有错误的情况下在特定目标中创建数据透视表?

时间:2017-07-17 14:47:49

标签: excel vba excel-vba pivot-table

我一直在广泛研究通过vba创建数据透视表,并且面临一些我无法找到解决方案的复杂问题。我正在尝试在“Pivot”工作表的第4列中创建一个数据透视表。当我尝试运行我的代码时,我得到:

  

“运行时错误1004:Worksheet类的数据透视表方法失败。”

有人可以帮忙吗?我对vba还很新。 这是我的代码,我在第二行继续收到错误:

 Sub PivotTable()
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Information").UsedRange).CreatePivotTable TableDestination:="Pivot!R1C4", TableName:="PivotTable", DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1)
With ActiveSheet.PivotTables("PivotTable").PivotFields("PN")
  .Orientation = xlRowField
 .Position = 1
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Commit")
 .Orientation = xlColumnField
 .Position = 1
End With
ActiveSheet.PivotTables("PivotTable").AddDataField ActiveSheet.PivotTables("PivotTable").PivotFields("Qty"), "Sum", xlSum
End Sub

1 个答案:

答案 0 :(得分:1)

您正在寻找类似下面的代码(代码注释中的解释):

Option Explicit

Sub AutoPivotTable()

Dim Sht As Worksheet
Dim PvtSht As Worksheet
Dim SrcData As Range
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable

'-- Determine the data range you want to pivot --
' Set the Worksheet object
Set Sht = ThisWorkbook.Worksheets("Information")
Set SrcData = Sht.UsedRange '1:Z10000").Address(False, False, xlR1C1, xlExternal)

' Set the Pivot Cache from Source Data
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData.Address(False, False, xlA1, xlExternal))

' Set the Worksheet object where the Pivot Table will be loated
Set PvtSht = ThisWorkbook.Worksheets("Pivot")

On Error Resume Next
'Set the pivot table object
Set PvtTbl = PvtSht.PivotTables("PivotTable") ' check if "PivotTable" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then '<-- Pivot Table not created >> create it
    ' create a new Pivot Table in "Pivot" sheet
    Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("D1"), TableName:="PivotTable")
    With PvtTbl
        With .PivotFields("PN")
            .Orientation = xlRowField
            .Position = 1
        End With
        With .PivotFields("Commit")
            .Orientation = xlColumnField
            .Position = 1
        End With
        .AddDataField .PivotFields("Qty"), "Sum of Qty", xlSum
    End With

Else ' just refresh the Pivot cache with the updated Range
    PvtTbl.ChangePivotCache PvtCache
    PvtTbl.RefreshTable
End If

End Sub