简体   繁体   中英

VBA 2 Pivot Tables different sheets

I have searched the web, but I'm having trouble finding a solution to my issue. I have a workbook with 2 tabs of data. I am using VBA to create 2 pivot tables on 2 different sheets. The code runs through the first pivot table perfectly. The Second set of code for the second pivot table stops at the pivot Cache. Any ideas?

 Dim sht As Worksheet
 Dim pvtCache As PivotCache
 Dim pvt As PivotTable
 Dim StartPvt As String
 Dim SrcData As String

 Dim finRow As String
  With ActiveWorkbook
  finRow = Sheets("WorbookName").Range("A200000").End(xlUp).Row
   SrcData = Sheets("WorkbookName").Name & "!" & Range("A1:I" & finRow).Address(ReferenceStyle:=xlR1C1)
  `End With`

  'Create a new worksheet
  Set sht = Sheets.Add

  'Pivot starting point?
   StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)

  'Create Pivot Cache from Source Data`
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
   SourceType:=xlDatabase, _
    SourceData:=SrcData)

  'Create Pivot table from Pivot Cache
   Set pvt = pvtCache.CreatePivotTable( _
   TableDestination:=StartPvt, _
   TableName:="PivotTable1")


   Set pvt = ActiveSheet.PivotTables("PivotTable1")`

 ================ Second Pivot table code  

Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String`

'Pivot table range
Dim finRow As String
With Sheets("Data")
finRow = Sheets("Data").Range("A200000").End(xlUp).Row
  SrcData = ActiveSheet.Name & "!" & Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
 End With

 'Create a new worksheet

  Set sht = Sheets.Add

 'Where do you want Pivot Table to start?
   StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)

   'Create Pivot Cache from Source Data`
   Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Create Pivot table from Pivot Cache
  Set pvt = pvtCache.CreatePivotTable( _
    TableDestination:=StartPvt, _
    TableName:="PivotTable2")

Any help provided is much appreciated. Thank you, Matt

At this point in your code, ActiveSheet is where you placed the previous pivot table, not on the sheet where you are intending to pull data. In both cases you use a With statement, but do not use.

Dim finRow As String
With Sheets("Data")
finRow = Sheets("Data").Range("A200000").End(xlUp).Row
  SrcData = ActiveSheet.Name & "!" & Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
 End With

Try modifying...

Dim finRow As Long
With Sheets("Data")
  finRow = .Range("A200000").End(xlUp).Row
  SrcData = .Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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