创建多个数据透视表我已经成功地通过使用VBA创建的数据透视表,但现在我想在两个单独的工作表,2和3。但是,创建两个数据透视表我的脚本VBA只创建一个数据透视表,甚至尽管我已经设置了2个透视表变量:PT1和PT2以及2个透视缓存变量:PTCache1和PTCache2。原始数据在工作表1中,我将其设置为RawData。
下面是我的脚本。请帮我解决我在这里失踪的事情。谢谢。在VBA
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
你应该删除On Error Goto Next,看看你得到了什么错误。 –
您是否尝试过注释'Set PTCache2 ...',并且仅对两个数据透视表使用PTCache1? –
@BobPhillips不幸的是,我为Excel VBA一个小白,错误消息意味着没有多少给我。这些代码实际上就是我在YouTube中发现的一些小调整,以适合我的数据集。谢谢。 – lukayl