Excel VBA透视表按条形码过滤

时间:2014-04-02 06:47:37

标签: excel vba excel-vba

我一直在尝试创建sub,这有助于通过选择几个条形码来过滤商品列表。我知道我可以手动完成,但它很长很令人沮丧,因为大约有2000个独特的条形码。我已经记录了一个宏,并在这里找到了一些类似的答案,但是我得到一个错误“运行时错误'1004':应用程序定义或对象定义的错误'当PI.value被赋值为true或false时它会卡住:”PI .Visible = True; Pi.Visible = False“。

代码:

  

Private Sub CommandButton1_Click()

Dim MyNames() As Variant
Dim objPivotField As PivotField
Dim i As Long
Dim PI As PivotItem
Set objPivotField = _
ActiveSheet.PivotTables("PivotTable1").PivotFields(Index:="[Prekė].[Barkodas].[Barkodas]")
MyNames = Array("4770349225872", "4770033220077", "7622400004773")
With ActiveSheet.PivotTables("PivotTable1").PivotFields(Index:="[Prekė].[Barkodas].[Barkodas]")

    For i = LBound(MyNames) To UBound(MyNames)

    For Each PI In .PivotItems
        If PI.Name = MyNames(i) Then
        PI.Visible = True
    Else
        PI.Visible = False
    End If
    Next PI
    Next i
End With End Sub

这是我为过滤录制的宏:

ActiveSheet.PivotTables("PivotTable1").PivotFields( _
    "[Prekė].[Barkodas].[Barkodas]").VisibleItemsList = Array("", _
    "[Prekė].[Barkodas].&[4750398000132]", "", "[Prekė].[Barkodas].&[4046234141238]", _
    "[Prekė].[Barkodas].&[4770248342625]")

1 个答案:

答案 0 :(得分:0)

如上面评论中所述,以下是我用VBA过滤数据透视表的方法:

pivot table setup

Option Explicit
Sub FilterPivotTable()

Dim PT1 As PivotTable
Dim PT1Barkodas As PivotField
Dim MyNames() As Variant
Dim PivotIdx As Long

'assign table, field and array values for easy reference
Set PT1 = ActiveSheet.PivotTables("PivotTable1")
Set PT1Barkodas = PT1.PivotFields("Barkodas")
MyNames = Array("4770349225872", "4770033220077", "7622400004773")

With PT1Barkodas

    'loop through all the barcodes
    For PivotIdx = 1 To PT1Barkodas.PivotItems.Count

        'logic to check if the current barcode is in the MyNames array
        If UBound(Filter(MyNames, .PivotItems(PivotIdx))) > -1 Then
            IsInArray = True
        Else
            IsInArray = False
        End If

        'if the barcode was not in the MyNames array, hide it
        If IsInArray = False Then
            .PivotItems(PivotIdx).Visible = False
        End If

    Next PivotIdx

End With

End Sub

根据MyNames运行此脚本过滤PivotTable1:

result