简体   繁体   中英

I am unable to add Data Field to my Pivot Table VBA

I get a runtime error

Unable to get the PivotTables property of Worksheet class

when I run the following code:

Sub UpdatePivot()

Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String

'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")
Set pt = ws3.PivotTables("PivotTable3")
Set pt = ws3.PivotTables("PivotTable3")
With pt.PivotFields(" May-17")
    .Orientation = xlColumnField
    .Function = xlSum
    .Position = 1
End With

End Sub

May I know what is wrong?

I did add the data source to a data model beforehand, and I'm not sure what exactly is causing the error.

Try the code below to try and trap your errors, explanations inside the code's comments:

Option Explicit

Sub UpdatePivot()

Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String

'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")

' 1ST: Trap the Pivot-Table object
On Error Resume Next
Set pt = ws3.PivotTables("PivotTable3")
On Error GoTo 0
If pt Is Nothing Then '<-- Pivot Table does't exist (Pivot Table renamed ?)
    MsgBox "Pivot-Table object Error!"
Else ' Pivot-Table object exists

    ' 2NDT: Trap the PivotField object
    On Error Resume Next
    Set pf = pt.PivotFields(" May-17")
    On Error GoTo 0
    If pf Is Nothing Then
        MsgBox "Pivot-Field object Error!"
    Else
        With pf
            .Orientation = xlColumnField
            .Function = xlSum
            .Position = 1
        End With
    End If
End If

End Sub

Thank you to @Shai Rado for all your feedback, extremely valuable. Also big big thanks to @jeffreyweir, I recorded a macro and found out the answer that I needed. The code for adding any pivot field from a data model is below:

ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
        "PivotTable3").CubeFields("[Measures].[Sum of May-17]"), "Sum of May-17"

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