2012-09-25 117 views
0

代碼正在運行!謝謝您的幫助!帶有動態數據範圍的Excel VBA宏數據透視表

我正在嘗試創建一個動態數據透視表,該數據表可以處理行數不同的數據。目前,我有28,300行,但這可能會每天更改。數據格式的

實施例,如下所示:表成品的

Case Number Branch  Driver 
1342   NYC   Bob 
4532   PHL   Jim 
7391   CIN   John 
8251   SAN   John 
7211   SAN   Mary 
9121   CLE   John 
7424   CIN   John 

實施例:

Driver NYC PHL CIN SAN CLE 
Bob  1  0  0  0  0 
Jim  0  1  0  0  0  
John  0  0  2  1  1  
Mary  0  0  0  1  0  

代碼如下:

Sub CreateSummaryReportUsingPivot() 
' Use a Pivot Table to create a static summary report 
' with model going down the rows and regions across 
Dim WSD As Worksheet 
Dim PTCache As PivotCache 
Dim PT As PivotTable 
Dim PRange As Range 
Dim FinalRow As Long 
Dim FinalCol As Long 
Set WSD = Worksheets("PivotTable") 

'Name active worksheet as "PivotTable" 
ActiveSheet.Name = "PivotTable" 

' Delete any prior pivot tables 
For Each PT In WSD.PivotTables 
    PT.TableRange2.Clear 
Next PT 

' Define input area and set up a Pivot Cache 
FinalRow = WSD.Cells(Application.Rows.Count, 1).End(xlUp).Row 
FinalCol = WSD.Cells(1, Application.Columns.Count). _ 
    End(xlToLeft).Column 
Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) 
Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _ 
    xlDatabase, SourceData:=PRange) 

' Create the Pivot Table from the Pivot Cache 
Set PT = PTCache.CreatePivotTable(TableDestination:=WSD. _ 
    Cells(2, FinalCol + 2), TableName:="PivotTable1") 

' Turn off updating while building the table 
PT.ManualUpdate = True 

' Set up the row fields 
PT.AddFields RowFields:="Driver", ColumnFields:="Branch" 

' Set up the data fields 
With PT.PivotFields("Case Number") 
    .Orientation = xlDataField 
    .Function = xlCount 
    .Position = 1 
End With 

With PT 
    .ColumnGrand = False 
    .RowGrand = False 
    .NullString = "0" 
End With 

' Calc the pivot table 
PT.ManualUpdate = False 
PT.ManualUpdate = True 

End Sub 
+1

您說這是在CSV文件上執行的?您沒有名爲「數據透視表」的表單有什麼可能? – scott

+0

我認爲Dim WSD作爲工作表,然後設置WSD =工作表(「數據透視表」)動態創建了名爲PivotTable的工作表。這不是這種情況嗎? – Liquidgenius

+0

手動將工作表從「Sheet1」重命名爲「數據透視表」,然後運行宏,繞過原始錯誤,以便您的洞察力得到幫助。現在我在註釋爲「從數據透視表緩存創建數據透視表」的部分出錯了。錯誤是「Method'CreatePivotTable'object'PivotCache'failed」 – Liquidgenius

回答

1

除了變化的行數以外,你使用VBA的原因是什麼?

如果您使用的是Excel 2007/2010,請根據原始數據創建常規表格/列表(Ctrl-L)。你也可以給它一個名字。然後創建一個數據透視表並使用表名作爲數據源。在添加行時,表格將展開,然後您可以刷新數據透視表(F5或使用VBA)。

如果您在Excel 2003中,也可以創建動態命名範圍。它稍微複雜一些(而且更難看),但如果你被困在舊版本中,我可以引導你完成它。

+0

我使用的是VBA,因爲這是一個自動化的過程,可以通過電子郵件每天收到的CVS文件上運行。我使用由電子郵件規則觸發的腳本運行宏。我正在使用適用於Mac的Excel 2011。它有VBA 14.0。 – Liquidgenius

+0

如果我可以使這個宏能夠工作,我可以完全自動化收集數據的過程,並且每天都會有更新的信息用作Tableau中可視化分析的基礎。 – Liquidgenius

+1

明顯的一個,但工作表完全稱爲數據透視表?表單(「數據透視表」)。激活彈出表單? – pedram

2

他們更改了PivotCaches的對象模型。您需要在2007-2010年(使用VBA版本7而不是版本6)的方法是

PivotCaches.Create