带有动态数据的VBA枢轴

时间:2017-04-06 17:35:17

标签: vba excel-vba pivot-table excel

我正在尝试从同一工作簿中的另一个选项卡获取数据提取数据,但是我收到错误。有什么想法吗?

Sub RefreshPivots()

Dim SrcData As String
Dim PivTbl As PivotTable
Dim lastrow As Long

Sheets("EXP 7004").Activate
lastrow = Sheets("EXP 7004").Range("a" & Rows.Count).End(xlUp).Row

SrcData = Sheets("EXP 7004").Range("$A$26:$AT$" & lastrow).Address(ReferenceStyle:=xlR1C1)

Set PivTbl = Sheets("EXP Pivot").PivotTables("PivotTable1")
Sheets("EXP Pivot").Activate

Sheets("EXP Pivot").PivotTables(PivTbl).ChangePivotCache Sheets("EXP Pivot"). _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)

End Sub

2 个答案:

答案 0 :(得分:1)

尝试下面的代码(解释在代码注释中):

Option Explicit

Sub RefreshPivots()

Dim ShtPivot    As Worksheet
Dim PivTbl      As PivotTable
Dim PivCache    As PivotCache
Dim SrcRng      As Range
Dim SrcData     As String
Dim lastRow     As Long

With Sheets("EXP 7004")
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

    Set SrcRng = .Range("A26:AT" & lastRow)
    SrcData = "EXP 7004!" & SrcRng.Address(True, True, xlA1)
End With

' set the Pivot Sheet
Set ShtPivot = Worksheets("EXP Pivot")

' set the Pivot Cache
Set PivCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcRng)

' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PivTbl = ShtPivot.PivotTables("PivotTable1") ' check if "PivotTable1" Pivot Table already created (in past runs of this Macro)

On Error GoTo 0
If PivTbl Is Nothing Then
    ' create a new Pivot Table in "EXP Pivot" sheet, start from Cell A1
    Set PivTbl = ShtPivot.PivotTables.Add(PivotCache:=PivCache, TableDestination:=ShtPivot.Range("A1"), TableName:="PivotTable1")

Else
     ' just refresh the Pivot cache with the updated Range (data in "EXP 7004" sheet)
    PivTbl.ChangePivotCache PivCache
    PivTbl.RefreshTable
End If

End Sub

答案 1 :(得分:1)

尝试这样......

Sub RefreshPivots()

Dim SrcData As Range
Dim PivTbl As PivotTable
Dim lastrow As Long

lastrow = Sheets("EXP 7004").Range("a" & Sheets("EXP 7004").Rows.Count).End(xlUp).Row

Set SrcData = Sheets("EXP 7004").Range("$A$26:$AT$" & lastrow)
Set PivTbl = Sheets("EXP Pivot").PivotTables("PivotTable1")

PivTbl.ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)

End Sub