设置数据透视表缓存时收到错误。即在此行:-
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable2")
我在另一个工作簿中使用了此宏,但没有收到此错误。
Sub PivTable()
'
' Insert a pivot table
'
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim ws As Worksheet
Dim x As Long
Set ws = Worksheets("Cash Month End")
With ws
x = .Range("b999999").End(xlUp).Row
End With
'Data Range to pivot
SrcData = "Cash Month End!(R4C1:R" & x & "C24)"
' Insert Sheet
Sheets.Add.Name = "Cash Pivot"
'Where the pivot must start
StartPvt = "Cash Pivot!R3C1"
'Create the pivot cache
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot Table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="PivotTable2")
'Add fields
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Segment")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable2").AddDataField ActiveSheet.PivotTables( _
"PivotTable2").PivotFields("No."), "Sum of No", xlSum
End Sub