数据透视表“无效的过程调用或参数”

时间:2019-12-18 10:48:24

标签: excel vba pivot-table

所以我现在正在做的是,我有一个VBA代码,该代码打开一个文件,然后重新格式化excel文件,我将该代码分配给该代码的按钮。 重新格式化文件后,我需要基于重新格式化的excel数据创建数据透视表。

因此,我在打开并运行的excel文件的模块中编写了数据透视表代码。数据透视表已成功创建。但是,当我将代码复制到打开excel文件并将其重新格式化的主文件中时,出现错误

  

“无效的过程调用或参数”。

当我尝试添加数据透视表时出现错误。

 Dim ws As Worksheet
 Dim pc As PivotCache
 Dim pt As PivotTable

LastRow = Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    ' set the Pivot-Cache Source Range with the values found for LastRow and LastCol
    Set PRange = Range("A1", Cells(LastRow, LastCol))

    If ThisWorkbook.PivotCaches.Count = 0 Then

        Set pc = ThisWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=PRange, _
        Version:=xlPivotTableVersion15)

    Else
        Set pc = ThisWorkbook.PivotCaches(1)
    End If

 Set ws = Worksheets.Add
 Range("A3").Select

 ' the next line is where the error happens
 Set pt = ws.PivotTables.Add( _
 PivotCache:=pc, _
 Tabledestination:=ActiveCell, _
 TableName:="PIVOTO")

 Set Pf = pt.PivotFields("Driver Name")
 Pf.Orientation = xlRowField

 Set Pf = pt.PivotFields("Over Speeding")
 Pf.Orientation = xlDataField

1 个答案:

答案 0 :(得分:0)

您需要在同一工作簿中创建PivotCache和PivotTable。这样的事情。

Sub Sample()
    Dim pc As PivotCache
    Dim pt As PivotTable
    Dim wbThis As Workbook, wbNew As Workbook

    Set wbThis = ThisWorkbook
    Set wb = Workbooks.Add

    'SourceData:=PRange
    Set pc = wb.PivotCaches.Create( _
            SourceType:=xlDatabase, _
            SourceData:=wbThis.Sheets("Sheet1").Range("A1:B5"), _
            Version:=xlPivotTableVersion15)

    '~~> wb.Sheets(1).Range("A1") Change to respective range
    Set pt = wb.Sheets(1).PivotTables.Add( _
             PivotCache:=pc, _
             TableDestination:=wb.Sheets(1).Range("A1"), _
             TableName:="PIVOTO")
End Sub