简体   繁体   中英

How to handle pivot table error when a field is missing?

I wrote a macro that includes creating several pivot tables from monthly reports.

The reports do not always have all the fields which need to be filtered.

The macro gives the error

Object doesn't support this property or method.

Is there a way to include an IF statement within the table formatting commands so that it will skip fields that are missing?

The debug error message refers to the line: If HasPivotItem(.PivotFields("PH Rel Independent Risk Unit Credit Organization")

Dim PT As Excel.PivotTable
    Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            "Raw Data!R1C1:R480C37", Version:=xlPivotTableVersion14).CreatePivotTable( _
            TableDestination:="'Pivot of Certain Data'!R1C1", TableName:="Pivot of Certain Data", _
            DefaultVersion:=xlPivotTableVersion14)

    With PT
     With .PivotFields( _
        "field 1")
        .Orientation = xlRowField
        .Position = 1
     End With
    With .PivotFields( _
        "field 1")
        .PivotItems("item 1").Visible = False
        
        If HasPivotItem(.PivotFields("field 1"), "item 2") Then
        .PivotFields("field 1").PivotItems("item 2").Visible = False
        End If
        
        .PivotItems("item 3").Visible = False
   End With

You could use a function like this to check if the item exists:

Private Function HasPivotItem(ByRef pField As PivotField, ByVal Item As String) As Boolean
    On Error Resume Next
    HasPivotItem = Not IsNull(pField.PivotItems(Item))
    On Error GoTo 0
End Function

And use it like:

Dim PT As Excel.PivotTable
Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Raw Data!R1C1:R480C37", Version:=xlPivotTableVersion14).CreatePivotTable( _
        TableDestination:="'Pivot of Certain Data'!R1C1", TableName:="Pivot of Certain Data", _
        DefaultVersion:=xlPivotTableVersion14)

With PT.PivotFields("field 1")
    .Orientation = xlRowField
    .Position = 1

    .PivotItems("item 1").Visible = False

    If HasPivotItem(PT.PivotFields("field 1"), "item 2") Then
        .PivotItems("item 2").Visible = False
    End If

    .PivotItems("item 3").Visible = False
End With

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