excel - 更改数据透视表源
问题描述
我对以下代码有疑问:
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
.
提前感谢您帮助我。
卢卡斯
解决方案
我找到了解决方法(我记得几年前我已经做过这样的事情):
首先,我为将成为数据透视表源的范围添加了一个名称:
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)
希望将来能帮助别人。
卢卡斯
推荐阅读
- amazon-web-services - 文件系统 S3 或 EFS 的 AWS 存储选择?
- c++ - c++ 泛型 lambdas:模式类型推导
- javascript - 将用户上传的纹理加载到three.js中的几何图形
- python - 从 Scrapy 管道中引发关闭蜘蛛
- python - 动态添加和删除条目框 Tkinter
- node.js - 在节点服务器上,锁定公共图像以便只有 API 服务器可以下载它?
- python - 如何检测图像上的符号并保存?
- javafx-8 - 在 JAVAFX 中保留上一个场景中所做的更改
- python - 从图书馆目录中抓取信息
- c++ - 安卓工作室 C++
- begin()/end() 没有匹配的函数 [可能的 cmake 问题]