我对以下代码有疑问:
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)
希望将来对别人有帮助。
卢卡斯