简体   繁体   中英

EXCEL VBA: How to fix Pivot Table error when attempting to use UsedRange?

I am trying to create a simple pivot table with Gas on the column, Dash No. for the row, and my Qty for the input. I've been researching this question and cannot find a solution. When I try to run my code I keep getting

Error 1004: Application-defined or object-defined error.

Here is my code:

Sub CreatePivotTable()

Dim sheet As Worksheet
Set sheet = Worksheets("mac3")

Sheets.Add.Name = "Table"
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
sheet.UsedRange, Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Table!R3C1", TableName:="Pvt" _
, DefaultVersion:=xlPivotTableVersion14

    Sheets("Table").Select
    Cells(3, 1).Select
    With ActiveSheet.PivotTables("Pvt").PivotFields("Gas")
        .Orientation = xlColumnField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("Pvt").PivotFields("Dash")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("Pvt").AddDataField ActiveSheet.PivotTables( _
        "Pvt").PivotFields("Qty"), "Sum of Qty", xlSum
    Range("B4").Select
    Selection.Group Start:=True, End:=True, Periods:=Array(False, False, False, _
        False, True, False, False)
End Sub

Do you already have a "Pvt" in your Worksheet? It can cause this error, in that case you can try changing the sheet and table names to something else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM