I have successfully created a pivot table by using VBA, but now I would like to create two pivot tables in two separate worksheets, 2 and 3. But my scripted VBA only creates one pivot table, even though I already set 2 Pivot table variables: PT1 and PT2, and 2 pivot cache variables: PTCache1 and PTCache2. The raw data is in worksheet 1, which I set as RawData.
Below is my script. Please help me out what I am missing here. Thanks.
Private Sub CreatePivotTables()
Dim ReportC2 As Workbook, RawData As Worksheet, SanityA As Worksheet
Dim LastRow As Long, LastCol As Long, i As Long
Dim PTCache1 As PivotCache, PTCache2 As PivotCache, PT1 As PivotTable, PT2 As PivotTable
Set ReportC2 = Workbooks.Open(ScorecardAddr & "\" & C2Name)
Set RawData = ReportC2.ActiveSheet
With RawData
Columns("A:A").Insert
.Range("A1").Value = "Deal & SKU"
LastRow = .Range("B" & Rows.Count).End(xlUp).Row
LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
For i = 2 To LastRow
.Range("A" & i) = .Range("F" & i).Value & "|" & .Range("P" & i).Value
Next
End With
With RawData
Set PTCache1 = ActiveWorkbook.PivotCaches.Create(xlDatabase, Range(Cells(1, 1), Cells(LastRow, LastCol)))
Set PTCache2 = ActiveWorkbook.PivotCaches.Create(xlDatabase, Range(Cells(1, 1), Cells(LastRow, LastCol)))
End With
On Error Resume Next
With ReportC2
.Sheets.Add After:=.Sheets(.Sheets.Count), Count:=2
.Sheets(2).Name = "C2Pivot-Transactional"
Set PT1 = .Sheets(2).PivotTables.Add(PTCache1, Range("A7"), "C2PT1")
'put the fields in the pivot table
With PT1
.PivotFields("Deal & SKU").Orientation = xlRowField
.PivotFields("quantity").Orientation = xlDataField
.PivotFields("GrossSellto").Orientation = xlDataField
.PivotFields("Total BDD Rebate").Orientation = xlDataField
.PivotFields("Total FLCP Rebate").Orientation = xlDataField
End With
End With
With ReportC2
.Sheets(3).Name = "C2Pivot-Reseller"
Set PT2 = .Sheets(3).PivotTables.Add(PTCache2, Range("A7"), "C2PT2")
'put the fields in the pivot table
With PT2
.PivotFields("Reseller ID").Orientation = xlRowField
.PivotFields("GrossSellto").Orientation = xlDataField
.CalculatedFields.Add "BDD + FLCP", "= 'Total BDD Rebate' + 'Total FLCP Rebate'"
.PivotFields("BDD + FLCP").Orientation = xlDataField
End With
End With
End Sub
Set PTCache2...
and only using PTCache1 for both pivot tables? – Mark Fitzgerald