如何为数据透视表创建动态范围?

时间:2019-07-10 20:24:50

标签: excel vba pivot-table

我正在尝试编写一个宏,该宏基于主电子表格中的数据在新工作表上创建数据透视表。如何调整我的代码来做到这一点?

我已经获得了处理静态数据的代码,但是只要数据是动态的,宏就无法工作。我认为问题在于第一行以“ srcData =”开头。下面的行已被注释掉,可以正常使用。

Option Explicit

Dim pivotSht As Worksheet
Dim dataSht As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim srcData As String
Dim pRange As Range
Dim lastR As Long
Dim lastC As Long

Public Sub buildPivot()

Set dataSht = Worksheets("OOB")

'Defines data range in "OOB" sheet
With dataSht
    lastR = .Cells(.Rows.Count, "D").End(xlUp).Row
    lastC = .Cells(4, .Columns.Count).End(xlToLeft).Column
    Set pRange = .Range(.Cells(1, "D1"), Cells(lastR, lastC))
End With

Sheets("OOB").Activate
srcData = ActiveSheet.Name & "!" & pRange.Address(ReferenceStyle:=xlR1C1)
'srcData = ActiveSheet.Name & "!" & Range("D1:U714").Address(ReferenceStyle:=xlR1C1)

'Delete old "PivotTable" worksheet if it exists
On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("PivotTable").Delete

'Create new sheet and name it "PivotTable"
Set pivotSht = Sheets.Add
ActiveSheet.Name = "PivotTable"

'Set location of pivot table
startPvt = pivotSht.Name & "!" & pivotSht.Range("A3").Address(ReferenceStyle:=xlR1C1)

'Define pivot cache
Set pCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=srcData)

'Creates pivot table from pivot cache
Set pTable = pCache.CreatePivotTable( _
    tabledestination:=startPvt, _
    TableName:="Open Order Book Table")

End Sub

The expected output is a pivot table using all data as the source, even with changing data.

0 个答案:

没有答案