在做数据透视表时,我仍然遇到相同的错误“ 13”“类型不兼容”。
Sub tracer()
Dim cache As PivotCache
Dim table As PivotTable
Dim prange As range
Dim lastrow As Long
Dim lastcol As Long
lastrow = data.Cells(data.Rows.count, "A").End(xlUp).Row
lastcol = 15
Set prange = data.Cells(1, 1).Resize(lastrow, lastcol)
graphe_clos.Select
Set cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=prange)
Set table = cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
感谢您的帮助
答案 0 :(得分:1)
将SourceData
分配给PivotCache
的更安全方法是使用以下行
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
添加第四个参数xlExternal
会验证该范围是否也在提取工作表的名称。
查看代码注释中的更多解释。
修改后的代码
Sub tracer()
Dim Cache As PivotCache
Dim Table As PivotTable
Dim pRange As Range
Dim LastRow As Long
Dim LastCol As Long
' use With statement to shorten and fully qualify all your nested objects
With Data
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastCol = 15
' set the Range of the Pivot's data
Set pRange = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
' graphe_clos.Select '<-- you don't need to "Select" the sheet in order to create the Pivot-Table
End With
' set the Pivot Cache
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
' set the Pivot Table
Set Table = Cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
关于您的最新问题,请修改:
With ActiveSheet.PivotTables("Terminator").PivotFields("Evt F")
使用
With Table.PivotFields("Evt F")
因为您已经将PivotTable
对象设置为Table
。