VBA对于工作簿更新数据源范围内的每个数据透视表

时间:2017-01-05 10:45:37

标签: excel-vba vba excel

我正在尝试遍历工作簿中的每个工作表,并在刷新之前将所有数据透视表数据范围重置为范围(“D1_Data”)。 目前使用以下代码获得运行时错误“1004”并且有点卡住,任何想法?

请注意,“TemplateWB”已经预先设置在我的代码中作为代码当前正在运行的工作簿的位置。

'Set Dim
    Dim PT As PivotTable
    Dim WS As Worksheet

'Set D1_Data
    TemplateWB.Sheets("Data_1").Range(Cells(1, 1), Cells(NewLastRow, NewLastColumn + 4)).Name = "D1_Data"

    For Each WS In TemplateWB.Worksheets

        For Each PT In WS.PivotTables

        With PT.PivotCache
            .SourceData = Range("D1_Data").Address(True, True, xlR1C1, True)
            .Refresh
        End With

        Next PT

    Next WS

1 个答案:

答案 0 :(得分:1)

尝试下面的代码(我在不同的工作表上的多个数据透视表上测试了它并且它有效。)

Option Explicit

Sub AutoRefreshPivot()

Dim WS As Worksheet
Dim PT As PivotTable
Dim PTCache As PivotCache

Dim NewLastRow As Long, NewLastColumn As Long
Dim TemplateWB As Workbook    

' values for my internal testing
'Set TemplateWB = ThisWorkbook
'NewLastRow = 11
'NewLastColumn = 4

'Set D1_Data
TemplateWB.Sheets("Data_1").Range(Cells(1, 1), Cells(NewLastRow, NewLastColumn + 4)).Name = "D1_Data"

For Each WS In TemplateWB.Worksheets

    For Each PT In WS.PivotTables
        ' set Pivot Cache to updated data source range (per each Pivot Table)
        Set PTCache = TemplateWB.PivotCaches.Create(SourceType:=xlDatabase, _
            SourceData:=Range("D1_Data").Address(True, True, xlR1C1, True), _
            Version:=xlPivotTableVersion14)

        With PT
            .ChangePivotCache PTCache
           ' .Refresh
        End With
        ' need to clear the cache every time after being used for a Pivot table
        Set PTCache = Nothing
    Next PT
Next WS

End Sub