2016-08-04 87 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