I Forte Si Daja
I Forte Si Daja

Reputation: 45

Check if a PT table Data field exists VBA

enter image description here

My code runs perfect... but somehow it adds a data field every time it runs. I tried to test it if it exists with If pf.Orientation = xlDataField = True Then...("Don't add xlDataField")... Still no results.

I am pretty sure I am missing something important here otherwise the code runs good. Is there a way not to add another field if it already exists?.

Sub Import()

    Dim ws As Worksheet, pvtCache As PivotCache
    Dim wsp As Worksheet
    Dim pf As PivotField, pt As PivotTable

    Set wsp = Sheets("Pivot")
    Set pt = wsp.PivotTables("PivotTable")

    ActiveWorkbook.RefreshAll

    Sheets("TP_Coois").Cells.Replace ",", "", xlPart
    Set pf = pt.PivotFields("Sales")

    If pf.Orientation = xlDataField = True Then  '***I believe here is something wrong***
        pt.PivotCache.Refresh
    Else
        With pf
            .Orientation = xlDataField
            .Function = xlSum
        End With

        pt.PivotCache.Refresh
    End If

End Sub

Any Help is appreciated

Upvotes: 0

Views: 1818

Answers (1)

Brian M Stafford
Brian M Stafford

Reputation: 8868

Try changing your conditional from:

If pf.Orientation = xlDataField = True Then

To this:

If pf.Orientation = xlDataField Then

Upvotes: 1

Related Questions