2016-08-04 89 views
0

我正在玩这段小小的代码。如何创建数据透视表并使用VBA命名它?

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

我想通过一系列的单元格循环,并根据我有一些数据集创建一堆枢轴。我有循环工作正常,我记录了一个宏应该做我想做的。我无法弄清楚的是数据透视表的命名约定。每次我打开宏记录器并单击事件序列时,似乎会增加1。我敢肯定的问题是在这里:

表名:=“PivotTable9”

我试图清除数据透视表的缓存,以重置表的名称,但没有奏效。

任何想法这里有什么问题吗?

+0

它看起来像你基于相同的透视缓存创建多个数据透视表。对我来说,问题看起来像是您试图在同一个单元格上的同一工作表上先前创建的表格上创建每个数据透视表。尝试在每个循环迭代中移动“TableDestination”(可能最简单的是每个PT都有一个新的工作表)。如果你的'TableName'已经存在,Excel会自动增加你的数据透视表名称。所以你也必须在循环的每次迭代中为每个PT创建一个唯一的名称。 – PeterT

+0

这可能是你说的。你能发布一些示例代码吗?我试过一堆东西,没有任何东西在为我工作。我可以在使用Excel 2003的另一台机器上执行此操作。我不知道Excel 2010为何无法处理它。 – ryguy7272

回答

1

您正在寻找的过程是分别建立PivotTable的每个部分。它可以更轻松地追踪发生的问题和错误。下面的代码示例演示如何设置通用的PivotCache,然后从该单一通用缓存中创建一个PivotTables

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

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 
+0

这是一件美丽的事!谢谢。另外,我发现这个链接是有帮助的。 http://analysistabs.com/excel-vba/pivot-tables-examples/ – ryguy7272