我如何创build一个数据透视表并使用VBA命名?

我正在玩这个小小的代码。

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ "Personnel&Facilities Detail!R3C1:R105279C21", Version:=xlPivotTableVersion14 _ ).CreatePivotTable TableDestination:="Corporate Communications!R1C1", _ TableName:="PivotTable9", DefaultVersion:=xlPivotTableVersion14 

我试图通过一系列的单元格来循环,并基于一些数据集来创build一堆枢轴。 我有循环工作正常,我logging了一个macros应该做我想要的。 我无法弄清楚的是数据透视表的命名约定。 每次我打开macroslogging器,并且点击事件顺序,它似乎增加1。 我很确定问题在这里:

表名:= “PivotTable9”

我试图清除数据透视表的caching来重置表名,但没有奏效。

任何想法这里有什么不对?

你正在寻找的过程是分别build立PivotTable每个部分。 这样可以更轻松地追踪出现的问题和错误。 下面的代码示例演示如何设置一个通用的PivotCache ,然后从该单一的通用caching中创build大量PivotTables

这个例子中缺less许多东西,比如检查同名的工作表,对可以创build的枢轴数的上限和下限,以及为每个表添加字段。

 Option Explicit Sub test() Dim dataArea As Range 'Set dataArea = ThisWorkbook.Sheets("Personnel&Facilities Detail").Range("A3:U105279") Set dataArea = ThisWorkbook.Sheets("RawData").Range("A1:L250") CreateAllPivots dataArea, 5 End Sub Sub CreateAllPivots(ByRef dataArea As Range, ByVal numPivots As Integer) '--- given an input range and the number of Pivot Tables to create, ' this sub creates a single, common Pivot Cache and then new ' Pivot Tables (each on its own worksheet) '--- perform any parameter checks, such as numPivots > 0 '--- create the common pivot cache for all tables Dim ptWB As Workbook Dim ptCache As PivotCache Set ptWB = ThisWorkbook Set ptCache = ptWB.PivotCaches.Create(SourceType:=xlDatabase, _ SourceData:=dataArea, _ Version:=xlPivotTableVersion14) '--- define the base name of the PT worksheets Dim ptName As String Dim ptSheetName As String ptName = "CorpCommPT" ptSheetName = "Corp Communications - " '--- set up all the pivot tables Dim i As Integer Dim ptSheet As Worksheet Dim newPTName As String Dim thisPivot As PivotTable For i = 1 To numPivots Set ptSheet = ptWB.Sheets.Add ptSheet.Name = ptSheetName & i newPTName = ptName & i Set thisPivot = ptCache.CreatePivotTable(TableDestination:=ptSheet.Range("A1"), _ TableName:=newPTName, _ DefaultVersion:=xlPivotTableVersion14) '--- potentially set up the pivot fields for the new table here Next i End Sub