使用 vba 更改枢轴源将不起作用

change pivot source using vba won't work

让 vba 更改多个数据透视表的数据源让我感到困惑。 我一直在阅读许多建议,到目前为止,其中 none 对我有所帮助。我不明白我做错了什么所以我最终在这里问我的问题。

这是我努力实现的目标: 我有多个包含数据透视表的文件必须更改,因为已插入列并且我的数据透视表数据源已更改。我想将其更改为正确的范围。我创建了这段代码:

Sub change_pivotsource()
Dim pt As PivotTable
Dim pts As PivotTables
Dim pt_source As String
Dim ws As Worksheet
Dim wb As Workbook

Set wb = ActiveWorkbook

workbookname = ActiveWorkbook.Name
sheetname = Left(workbookname, Len(workbookname) - 5)
pt_source = "'" & sheetname & "'!$A:$T"


For Each ws In wb.Worksheets
    For Each PivotTable In ws.PivotTables
      pt.SourceData = pt_source
    Next PivotTable
Next ws


End Sub

我正在使用工作簿名称来包含作为最终数据源位置的字符串。

如何将 pt_source 作为工作簿中每个数据透视表的数据透视表源? 很多次我收到 "object or block variable with is not set" 错误

编辑 1:

此代码在执行过程中出现错误 7:内存不足: 然后突出显示 "pt_source =" 行。

Sub change_pivotsource()
Dim ws As Worksheet
Dim wb As Workbook
Dim pt As PivotTable
Dim sheetname As String
Dim pt_source As String
Dim workbookname As String

workbookname = ThisWorkbook.Name
sheetname = Left(workbookname, Len(workbookname) - 5)
pt_source = Sheets(sheetname).Range("$A:$T")

For Each ws In ThisWorkbook.Worksheets
      For Each pt In ws.PivotTables
        pt.ChangePivotCache _
        wb.PivotCaches.Create(SourceType:=xlDatabase, _
              SourceData:=pt_source)

      Next pt
Next ws
'workbook.save
End sub

这段代码解决了我的问题:

Sub UpdatePivotCaches()
' Updates each pivot cache in the current workbook.
Dim pt As PivotTable        ' Used to loop over each pivot table.
Dim ws As Worksheet         ' Used to loop over each work sheet.
Dim sheetname As String
Dim pt_source As String
Dim workbookname As String

workbookname = ThisWorkbook.Name
sheetname = Left(workbookname, Len(workbookname) - 5)


    ' Loop over each sheet.
    For Each ws In ActiveWorkbook.Sheets

        ' Loop over each pivot table on the sheet.
        For Each pt In ws.PivotTables

            ' Update the pivot cache.
            pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create(xlDatabase, "'" & sheetname & "'!$A:$T", xlPivotTableVersion14)
        Next
    Next
End Sub

解决方案的关键可能是版本参数(请参阅此问题下方的评论)。 感谢目的地数据

Pivot tables 从 pivot cache 获取数据。我们需要更改的正是这个对象。此过程替换连接到当前工作簿中每个数据透视表 table 的缓存。

Sub UpdatePivotCaches()
' Updates each pivot cache in the current workbook.
Dim pt As PivotTable        ' Used to loop over each pivot table.
Dim ws As Worksheet         ' Used to loop over each work sheet.


    ' Loop over each sheet.
    For Each ws In ActiveWorkbook.Sheets

        ' Loop over each pivot table on the sheet.
        For Each pt In ws.PivotTables

            ' Update the pivot cache.
            pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Sheet1'!C8:D12", xlPivotTableVersion14)
        Next
    Next
End Sub

我已经对新数据源进行了硬编码 (...'Sheet1'!C8:D12...),但您可以通过 parameterising 范围地址来改进此过程。

如果您遇到 VBA 的问题,请尝试 macro recorder。这会将您的手动操作转换为 VBA。这是一个非常方便的工具。