代碼正在運行!謝謝您的幫助!帶有動態數據範圍的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
您說這是在CSV文件上執行的?您沒有名爲「數據透視表」的表單有什麼可能? – scott
我認爲Dim WSD作爲工作表,然後設置WSD =工作表(「數據透視表」)動態創建了名爲PivotTable的工作表。這不是這種情況嗎? – Liquidgenius
手動將工作表從「Sheet1」重命名爲「數據透視表」,然後運行宏,繞過原始錯誤,以便您的洞察力得到幫助。現在我在註釋爲「從數據透視表緩存創建數據透視表」的部分出錯了。錯誤是「Method'CreatePivotTable'object'PivotCache'failed」 – Liquidgenius