添加pivotcache

时间:2016-09-29 05:01:52

标签: excel vba excel-vba pivot-table

这会返回类型不匹配错误,我不知道原因。

昨天我问了同样的问题,我发现有一些合并的单元格,因此我今天删除了合并单元格,但仍然无法提供相同的错误

该代码适用于其他工作表数据,但它会返回该特定工作表的错误。

我试过了:

Set wD = Sheets.Add
ThisWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=wS.UsedRange).CreatePivotTable _
TableDestination:=wD.Range("A3")

这个

Set wD = Sheets.Add
ThisWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=wS.Range("A1").CurrentRegion).CreatePivotTable _
TableDestination:=wD.Name & "!R3C1"

这是源数据表的样子

Source Data Sheet

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

Sub UpdatePivot()

Dim wD                              As Worksheet
Dim wS                              As Worksheet

Dim PvtTbl                          As PivotTable
Dim PvtCache                        As PivotCache
Dim PvtRangeStr                     As String


Set wS = Sheets("inventory master")
Set wD = Sheets.Add

PvtRangeStr = "'" & wS.Name & "'!" & wS.UsedRange.Address

' for debug
Debug.Print PvtRangeStr

' set Pivot Cache using another reference to the range
Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PvtRangeStr, Version:=xlPivotTableVersion14)    

' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = wD.PivotTables("PivotTable1")

On Error GoTo 0
If PvtTbl Is Nothing Then

    ' create a new Pivot Table in wD Sheet, start from Cell A3
    Set PvtTbl = wD.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=wD.Range("A3"), TableName:="PivotTable1")
Else
    ' just refresh the Pivot cache with the updated data
    PvtTbl.ChangePivotCache PvtCache
    PvtTbl.RefreshTable
End If

End Sub
相关问题