我一直在尝试创建一个填充数据透视表的宏。但是,我一直得到这个
在运行时错误440
Set Cache
行中。
以前,我遇到了其他运行时错误,但这些错误很容易解决。我不明白为什么在这种情况下不允许使用PivotCaches.Create
方法。 SOS,请帮忙!
这是代码:
' Declare variables for pivots
Dim pivotWB As Workbook
Dim RawDataWS As Worksheet
Dim dataLocation As Range
Dim cache As PivotCache
Dim table As PivotTables
' name and set the workbook for pivot tables
folderName = ThisWorkbook.Sheets(1).Cells(5, 13).Value
fileName = ThisWorkbook.Sheets(1).Cells(6, 13).Value
extName = ThisWorkbook.Sheets(1).Cells(7, 13).Value
wbAddress = folderName & "\" & fileName & "." & extName
Set pivotWB = Workbooks.Open(wbAddress)
Set dataLocation = pivotWB.Sheets("Raw Data").Range("A:AK")
Set cache = pivotWB.PivotCaches.Create(SourceType:=xlDatabase,_
sourceData:=dataLocation, Version:=xlPivotTableVersion14)
For i = 1 To 5
' create new worksheet and pivot table
pivotWB.Sheets.Add Before:=Sheets(1)
pivotWB.Sheets(1).Name = Left(toPivot(i), 30)
cache.CreatePivotTable TableDestination:=pivotWB.Sheets(1).Cells(1, 1), TableName:=toPivot(i) & " Pivot Table"
' set rows
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Rejection Category Description")
.Orientation = xlRowField
.Position = 1
End With
' set columns
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Post Period")
.Orientation = xlColumnField
.Position = 1
End With
' set values
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Procedure Code")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
.Name = "Count of Code"
End With
With pivotWB.Sheets(1).PivotTables(toPivot(i) & " Pivot Table").PivotFields("Amount")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.NumberFormat = "$#,##0"
.Name = "Sum of Amount"
End With
Next i
答案 0 :(得分:0)
在@Rory注释之后,您需要使用PivotCache
属性设置Address
对象。
此外,将table
对象设置为PivotTable
将创建更容易,更短的代码。
请参见下面的代码,代码注释中有更多注释。
修改后的代码
' --- set the Pivot Cache ---
Set cache = pivotWB.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=dataLocation.Address(False, False, xlR1C1, xlExternal))
For i = 1 To 5
' create new worksheet and pivot table
pivotWB.Sheets.Add Before:=Sheets(1)
pivotWB.Sheets(1).Name = Left(toPivot(i), 30)
' --- set the Pivot-Table Object ---
Set table = cache.CreatePivotTable(TableDestination:=pivotWB.Sheets(1).Cells(1, 1), TableName:=toPivot(i) & " Pivot Table")
With table ' <-- after you set the table object, you can simply use With statement now
' set rows
With .PivotFields("Rejection Category Description")
.Orientation = xlRowField
.Position = 1
End With
' set columns
With .PivotFields("Post Period")
.Orientation = xlColumnField
.Position = 1
End With
' set values
With .PivotFields("Procedure Code")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
.Name = "Count of Code"
End With
With .PivotFields("Amount")
.Orientation = xlDataField
.Position = 2
.Function = xlSum
.NumberFormat = "$#,##0"
.Name = "Sum of Amount"
End With
End With
Next i