1
我想寫一些VBA,將在新選項卡中構建數據透視表。當我運行代碼時,創建數據透視表緩存時出現類型不匹配錯誤。VBA樞軸表
的代碼如下,任何幫助,將不勝感激...希望重新審視它可以發現什麼,我缺少的
Sub makeAPivotTable()
Dim sSheet, sSheet2 As Worksheet 'sSheet is where the data is, sSheet2 is where the pivot will be built
Dim cCache As PivotCache
Dim ptTable As PivotTable
Dim rRange As Range
Dim rLastRow, cLastColumn As Long
' Insert the new sheet for the pivot table to reside
Application.DisplayAlerts = False
Sheets.Add Before:=ActiveSheet
ActiveSheet.name = "PivotTable"
Application.DisplayAlerts = True
Set sSheet2 = Worksheets("PivotTable")
Set sSheet = Worksheets("Interactions db")
' define the range (the data that you want to put into the pivot table
rLastRow = sSheet.Cells(Rows.Count, 1).End(xlUp).Row
cLastColumn = sSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set rRange = sSheet.Cells(1, 1).Resize(rLastRow, cLastColumn)
' create the cache for the pivot table
Set cCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=rRange). _
CreatePivotTable(TableDestination:=sSheet2.Cells(2, 2), _
TableName:="SalesPivotTable")
' insert the blank table
Set ptTable = cCache.CreatePivotTable _
(TableDestination:=sSheet2.Cells(1, 1), TableName:="SalesPivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("customer")
.Orientation = xlRowField
.Position = 1
End With
'Insert Column Fields
'With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Interaction Type")
'.Orientation = xlColumnField
'.Position = 1
'End With
'Insert Data Field
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("interactionType")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.name = "Person "
End With
' do some formatting
End Sub
如果我沒看錯的,應該是這樣的 - 集ptTable = sSheet2.PivotTables.Add(PivotCache:= CCACHE,TableDestination:= sSheet2.Range( 「A1」),表名:= 「SalesPivotTable」) – sktneer
還在開始時刪除sSheet2非常重要,因爲每次刪除樞軸高速緩存時都是如此e代碼運行時,它會拋出一個錯誤,因爲您不能有兩張具有相同名稱的工作表,並且每次創建新的數據透視緩存時都會不必要地增加no。工作簿中的數據透視表緩存因此是文件的大小。 – sktneer
@sktneer你是對的,有很多可能的錯誤處理要做,但首先我認爲PO需要解決他的代碼中的關鍵錯誤。但是,由於你的建議,我已經添加了(另一種方式) –