设置PivotField类

时间:2017-10-03 11:17:49

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

我创建了一个宏来自动化构建数据透视表的过程。宏执行得很好,但它一直显示错误1004.(但是,结果很好)。我提供以下代码。

'PIVOT TABLE

Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PRange As Range
Dim LastRow12 As Long
Dim LastCol As Long
Set PSheet = ActiveSheet
LastRow12 = PSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = PSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = PSheet.Cells(1, 1).Resize(LastRow12, LastCol)
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable TableDestination:=PSheet.Cells(2, 16), TableName:="PivotTable1"
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Destination")
.Orientation = xlRowField
.Position = 1
.Subtotals(1) = True
.Subtotals(1) = False
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("End Date")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Trucks")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "0.0"
.Name = "Trucks"
End With

1 个答案:

答案 0 :(得分:1)

尝试下面的代码,代码注释中的解释:

Option Explicit

Sub CreatePivot4()

Dim pvt As PivotTable
Dim PvtCache As PivotCache

Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PRange As Range
Dim LastRow12 As Long
Dim LastCol As Long

Set PSheet = ActiveSheet
With PSheet
    LastRow12 = .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set PRange = .Range(.Cells(1, 1), .Cells(LastRow12, LastCol))
End With

' Create Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange.Address(False, False, xlA1, xlExternal))

' Set the Pivot Table (already created in previous macro run)
On Error Resume Next
Set pvt = PSheet.PivotTables("PivotTable1")

On Error GoTo 0
If pvt Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it

     ' create a new Pivot Table in ActiveSheet sheet, start from Cell A1
    Set pvt = PSheet.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PSheet.Cells(2, 16), TableName:="PivotTable1")

    With pvt
        With .PivotFields("Destination")
            .Orientation = xlRowField
            .Position = 1
            .Subtotals(1) = True
            .Subtotals(1) = False
        End With
        With .PivotFields("End Date")
            .Orientation = xlColumnField
            .Position = 1
        End With
        With .PivotFields("Trucks")
            .Orientation = xlDataField
            .Position = 1
            .Function = xlSum
            .NumberFormat = "0.0"
            '.Name = "Trucks" ' * Why do you need to rename it ?
        End With
    End With
Else
    ' just refresh the Pivot table, with updated Pivot Cache
    pvt.ChangePivotCache PvtCache
    pvt.RefreshTable
End If

End Sub