从宏创建数据透视图时,运行时错误1004

时间:2019-01-30 10:21:41

标签: excel vba pivot-table

我写了一个宏在Excel中添加数据透视图。我得到

  

应用程序定义或对象定义的错误

在下面的行中

。 有人可以帮我吗?

Set DSheet = ActiveWorkbook.Worksheets("Sheet1")
Worksheets("Sheet1").Activate
LastRow = DSheet.Cells(DSheet.Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, DSheet.Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

Table1_Start_Line = 2
Table1_End_Line = Table1_Start_Line + LastRow
Column_Line = LastCol + 2
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion15).CreatePivotTable TableDestination:=DSheet.Cells(Table1_Start_Line, Column_Line), TableName:="PivotTable", DefaultVersion:=xlPivotTableVersion15

1 个答案:

答案 0 :(得分:0)

我认为这段代码可以满足您的需求。本质上,它会在插入新表之前删除现有表。

Private Sub RenewPivotTable()

    Dim DSheet As Worksheet
    Dim PTable As PivotTable
    Dim LastRow As Long, LastCol As Long
    Dim PRange As Range
    Dim Table1_Start_Line As Long, Column_line As Long

    Set DSheet = ActiveWorkbook.Worksheets("Sheet1")
    With DSheet
        If .PivotTables.Count Then
            .PivotTables(1).TableRange2.Clear
        End If
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set PRange = .Cells(1, 1).Resize(LastRow, LastCol)
    End With

    Table1_Start_Line = 2
    Column_line = LastCol + 2
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                                      SourceData:=PRange, _
                                      Version:=xlPivotTableVersion15).CreatePivotTable _
                                      TableDestination:=DSheet.Cells(Table1_Start_Line, Column_line), _
                                      TableName:="PivotTable", _
                                      DefaultVersion:=xlPivotTableVersion15
End Sub

我在Excel 2010中测试了它的Version14版本