枢纽分析表建立失败,发生执行阶段错误1004

时间:2018-06-23 12:59:07

标签: excel excel-vba pivot-table vba

该代码曾经在Office 365上运行。我现在在Office 2016上工作,并且在最后一行遇到运行时错误。输入是:

'Create a Pivot table called pt commission on sheet "Pivot Table" from the data on sheet2
Call ptSettings.CreatePivotTable("Pivot Table", Sheet2, "ptCommission")

在最后一行引发错误的子项是:

Sub CreatePivotTable(ptSheet As String, dSheet As Worksheet, ptName As String)

'Creates a pivottable called ptName on sheets(ptSheet) with the data from dsheet

Dim ptCache As PivotCache
Dim ptTable As pivotTable
Dim ptRange As Range
Dim lastRow As Long
Dim lastCol As Long

Application.DisplayAlerts = False

Worksheets(ptSheet).Delete
Sheets.Add before:=ActiveSheet
ActiveSheet.Name = ptSheet
Application.DisplayAlerts = True

lastRow = dSheet.Cells(Rows.Count, 2).End(xlUp).Row
lastCol = dSheet.Cells(2, Columns.Count).End(xlToLeft).Column

Set ptRange = dSheet.Cells(1, 1).Resize(lastRow, lastCol + 1)

Set ptCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=ptRange)

Set ptTable = ptCache.CreatePivotTable _
(TableDestination:=Sheets(ptSheet).Cells(3, 1), TableName:=ptName)

End Sub

1 个答案:

答案 0 :(得分:0)

为大家加油!

只是发现正在发生的事情。第二行中有数据,使得lastCol高于需要的值。然后,当我尝试从该范围创建数据透视表时,由于ptRange没有列标题,因此引发了错误。

我只有在尝试运行vs单步执行后才意识到,它出了一个不同的错误..哦,VBA。