0

When I run the below VBA code to create a pivot table, I get an "Invalid procedure or call argument error" when running the macro. The error is on the "Set PT" area.

I've defined worksheet objects but I also tried adjusting the "Table Destination" to directly reference the worksheet and I still get the same error.

Any idea what might be causing the error?

With wsData
    Dim PTCache As PivotCache
    Dim PT As PivotTable

    'Creates the Cache
    Set PTCache = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=.Range("A1").CurrentRegion)

    'Creates pivot table
    Set PT = wsPivot.PivotTables.Add( _
        PivotCache:=PTCache, _
        TableDestination:=wsPivot)

    'Defines fields
    With PT
        .PivotFields("Field 1").Orientation = xlRowField
        .PivotFields("Field 2").Orientation = xlRowField
        .PivotFields("Field 3").Orientation = xlRowField
        .AddDataField .PivotFields("Field 4"), "Field 4", xlCount
        .TableStyle2 = "PivotStyleMedium2"
    End With
End With
4
  • 1
    What's wsPivot? Commented Feb 7, 2018 at 20:33
  • Its a worksheet object, equal to something like '[Worksheet.xlsm]Sheets("Pivot")' Commented Feb 7, 2018 at 21:08
  • TableDestination argument requires a specified range. See PivotTables.Add Method Commented Feb 7, 2018 at 21:11
  • Thanks. Based off that information I tweaked that section to be: Set PT = wsPivot.PivotTables.Add( _ PivotCache:=PTCache, _ TableDestination:=wsPivot.Range("A3"), _ TableName:="Pivot Table") I still got the same error : "Run-time error '5': Invalid procedure call or argument" Commented Feb 7, 2018 at 21:32

1 Answer 1

1

I found the issue, rather than building the pivot cache from the ActiveWorkbook I used ThisWorkbook instead.

The following code ran without error:

With wsData
Dim PTCache As PivotCache
Dim PT As PivotTable

'Creates the Cache
Set PTCache = ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=.Range("A1").CurrentRegion)

'Creates pivot table
Set PT = wsPivot.PivotTables.Add( _
    PivotCache:=PTCache, _
    TableDestination:=wsPivot)

'Defines fields
With PT
    .PivotFields("Field 1").Orientation = xlRowField
    .PivotFields("Field 2").Orientation = xlRowField
    .PivotFields("Field 3").Orientation = xlRowField
    .AddDataField .PivotFields("Field 4"), "Field 4", xlCount
    .TableStyle2 = "PivotStyleMedium2"
End With
End With
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.