我正在尝试自动尝试更改"数据源" excel中的数据透视表。我已经尝试了大多数(如果不是全部)Google / Stack Overflow上提供的解决方案。但是我一直遇到以下错误。
Run-time error '5':
Invalid procedure call or argument
以下是我正在运行的代码失败。
Sub UpdateResourcePivots()
Dim pivotDataSheet As Worksheet
Dim dataSheet As Worksheet
Dim pivotLocation As String
Dim pivotDesignation As String
Dim startPoint As Range
Dim endPoint As Range
Dim dataRange As Range
Dim newRange As String
Dim lastRow As Integer
Dim newPivotCache As PivotCache
Set pivotDataSheet = ThisWorkbook.Worksheets("PivotData")
Set dataSheet = ThisWorkbook.Worksheets("Team Information")
pivotLocation = "pvtResourceLocation"
pivotDesignation = "pvtResourceDesignation" 'Dont worry about this one for now
Set startPoint = dataSheet.Range("A5")
lastRow = dataSheet.Range("A" & dataSheet.Rows.count).End(xlUp).row
Set endPoint = dataSheet.Range("O" & lastRow)
Set dataRange = dataSheet.Range(startPoint, endPoint)
newRange = "'" & dataSheet.name & "'!" & dataRange.Address(RowAbsolute:=True, ColumnAbsolute:=True, ReferenceStyle:=xlR1C1, External:=True)
' newRange = "'" & dataSheet.name & "'!" & dataRange.Address(ReferenceStyle:=xlR1C1) ' Tried this as well
Set newPivotCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=newRange, Version:=xlPivotTableVersion10)
With pivotDataSheet
.PivotTables(pivotLocation).ChangePivotCache newPivotCache 'Error thrown here.
End With
End Sub
错误发生在以下行:
.PivotTables(pivotLocation).ChangePivotCache newPivotCache
其他一些信息
我正在使用MS Office 2010(许可)。 我有一个数据源(一个包含20行和8列的小表;行将增长,因此宏)。在另一张纸上创建了两个数据透视表。在第三张纸上,我使用切片器过滤数据(仪表板)。
答案 0 :(得分:1)
更改代码,以便在将其分配给数据透视表时创建缓存:
With pivotDataSheet
.PivotTables(pivotLocation).ChangePivotCache ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=dataRange.Address(Referencestyle:=xlR1C1), Version:=xlPivotTableVersion10)