VBA - test if a value is a valid selection for a PivotField

后端 未结 2 829
自闭症患者
自闭症患者 2021-01-22 00:24

For a pivot table (pt1) on Sheet1, I use VBA to change the value of a filter field (filterfield) using the code below. Let\'s say values for field can be A, B or C



        
2条回答
  •  盖世英雄少女心
    2021-01-22 00:34

    You can iterate through the PivotItems and check the Name against your test.

    Sub CheckIfPivotFieldContainsItem()
    
        Dim pt As PivotTable
        Set pt = Sheet1.PivotTables(1)
    
        Dim test_val As Variant
        test_val = "59"
    
        Dim pivot_item As PivotItem
        For Each pivot_item In pt.PivotFields("C").PivotItems
            If pivot_item.Name = test_val Then
                Debug.Print "MATCHES"
            End If
        Next pi
    
    End Sub
    

    Relevant data shows that a match should exist and indeed it returns MATCHES.

    pivot data

提交回复
热议问题