使用vba改变枢轴源不会起作用

时间:2016-04-11 14:27:49

标签: vba excel-vba datasource pivot-table excel

我一直很困惑让vba改变多个枢轴的数据源。 我一直在阅读很多建议,到目前为止,他们都没有帮助过我。我不明白我做错了什么,所以我最终在这里问我的问题。

这是我尝试实现的目标: 我有多个带有枢轴的文件,因为已插入列并且我的透视数据源已更改,所以必须更改这些文件。我想将其改为正确的范围。我创建了这段代码:

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作为我工作簿中每个数据透视的枢轴源? 很多时候我得到一个"对象或块变量没有设置"错误

编辑1:

此代码在执行期间给出了错误7:内存不足: 然后它突出显示" pt_source =" -row。

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

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

1 个答案:

答案 0 :(得分:1)

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

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。这是一个非常方便的工具。