繁体   English   中英

具有动态数据范围的数据透视表的Excel VBA宏

[英]Excel VBA Macro for Pivot Table with Dynamic Data Range

代码正在工作! 谢谢您的帮助!

我正在尝试创建一个动态数据透视表,该表将对行数不同的数据起作用。 目前,我有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

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

 PivotCaches.Create

除了更改行数之外,您是否还在使用VBA?

如果您使用的是Excel 2007/2010,请从原始数据创建常规表/列表(Ctrl-L)。 您也可以为其命名。 然后创建数据透视表,并将表名称用作数据源。 添加行时,表将扩展,然后可以刷新数据透视表(F5或使用VBA)。

如果您使用的是Excel 2003,则还可以创建动态命名范围。 它稍微复杂一些(而且丑陋得多),但是如果您遇到较旧的版本,我可以指导您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM