首页 > 解决方案 > 更改数据透视表源

问题描述

我对以下代码有疑问:

Sub sChangePivotRange()

Dim lngLastRow as Long
Dim rngPivotRange as Range
Dim strPivotRange as String

lngLastRow = ActiveSheet.Range("C" & ActiveSheet.Rows.Count).End(xlUp).Row

Set rngPivotRange = ActiveSheet.Range("C5:AC" & lngLastRow)

strPivotRange = ActiveWorkbook.Path & "\[" & ActiveWorkbook.Name & "]" & ActiveSheet.Name & "!" & rngPivotRange.Address(ReferenceStyle:=xlR1C1)

ActiveSheet.PivotTables("RANKING").ChangePivotCache ActiveWorkbook.PivotCaches. _
        Create(SourceType:=xlDatabase, SourceData:= _
        "C:\[Ranks.xlsb]Ranks!R5C3:R117708C29" _
        , Version:=6)

ActiveSheet.PivotTables("RANKING").ChangePivotCache ActiveWorkbook.PivotCaches. _
        Create(SourceType:=xlDatabase, SourceData:= _
        strPivotRange _
        , Version:=6)

End Sub

这部分完美无缺:

ActiveSheet.PivotTables("RANKING").ChangePivotCache ActiveWorkbook.PivotCaches. _
            Create(SourceType:=xlDatabase, SourceData:= _
            "C:\[Ranks.xlsb]Ranks!R5C3:R117708C29" _
            , Version:=6)

虽然这部分导致错误:

ActiveSheet.PivotTables("RANKING").ChangePivotCache ActiveWorkbook.PivotCaches. _
            Create(SourceType:=xlDatabase, SourceData:= _
            strPivotRange _
            , Version:=6)

错误文本是:

“The PivotTable field name is not valid. To create a PivotTable report, you must use data that is organized as a list with labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.”

显然将?strPivotRange立即窗口结果与C:\[Ranks.xlsb]Ranks!R5C3:R117708C29.

提前感谢您帮助我。

卢卡斯

标签: excelvbapivot-table

解决方案


我找到了解决方法(我记得几年前我已经做过这样的事情):

首先,我为将成为数据透视表源的范围添加了一个名称:

ActiveWorkbook.Names.Add Name:="PIVOT_SOURCE", RefersToR1C1:="=Ranks!R5C3:R" & lngLastRow & "C29"

然后我使用这个名称作为数据透视表的来源:

ActiveSheet.PivotTables("RANKING").ChangePivotCache _
            ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="PIVOT_SOURCE", Version:=6)

希望将来能帮助别人。

卢卡斯


推荐阅读