数据透视表的VBA错误:对象_Global的错误1004范围失败

时间:2015-05-04 09:48:11

标签: excel vba excel-vba pivot-table

我在VBA中创建一个数据透视表,首先计算其范围,然后从中创建一个表。但是,它显示错误,所以有人可以纠正吗?它显示:

  

错误1004对象范围_Global失败。

Sub Pivottable()

    Dim NewRange As Range
    Dim n As Long

    Sheets("DUT1_Test51_excel").Select

    n = Worksheets("DUT1_Test51_excel").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

    Set NewRange = Range("A3" & ":" & "Q" & n)

    ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=Range(NewRange), _
    Version:=xlPivotTableVersion14). _
        CreatePivotTable _
        TableDestination:="DUT1_Test51_excel!R3C22", _
        TableName:="PivotTable1", _
        DefaultVersion:=xlPivotTableVersion14

    Sheets("DUT1_Test51_excel").Select
    Cells(3, 22).Select

    ActiveWorkbook.ShowPivotTableFieldList = True
    ActiveSheet.PivotTables("PivotTable1").AddDataField _
        ActiveSheet.PivotTables("PivotTable1").PivotFields("20431"), "Average of 20431", xlAverage
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("time")
        .Orientation = xlRowField
        .Position = 1
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

试试这个(将NewRange改为String):

Sub Pivottable()

    Dim NewRange As String
    Dim n As Long

    Sheets("DUT1_Test51_excel").Select

    n = Worksheets("DUT1_Test51_excel").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

    NewRange = "A3:Q" & n


   ActiveWorkbook.PivotCaches.Create( _
   SourceType:=xlDatabase, _
   SourceData:=Range(NewRange), _
   Version:=xlPivotTableVersion14). _
        CreatePivotTable _
        TableDestination:="DUT1_Test51_excel!R3C22", _
        TableName:="PivotTable1", _
        DefaultVersion:=xlPivotTableVersion14

    Sheets("DUT1_Test51_excel").Select
    Cells(3, 22).Select

    ActiveWorkbook.ShowPivotTableFieldList = True
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("20431"), "Average of 20431", xlAverage
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("time")
        .Orientation = xlRowField
        .Position = 1
    End With

End Sub