Filtrage du tableau pivotant Excel VBA par code à barres

J'ai essayé de créer un sous, qui aide à filterr la list des biens en sélectionnant quelques codes à barres. Je sais que je peux le faire manuellement, mais c'est très long et frustrant, car il existe environ ~ 2000 codes-barres uniques. J'ai enregistré une macro et j'ai trouvé quelques réponses similaires ici, mais j'ai une erreur "Erreur d'exécution" 1004 ': Application définie ou erreur définie par l'object "elle bloque quand PI.value est atsortingbuée true ou false:" PI .Visible = vrai; Pi.Visible = False ".

Code:

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 

Et voici Macro que j'ai enregistré pour le filtrage:

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

Comme indiqué ci-dessus dans les commentaires, voici la méthode que j'ai utilisée pour filterr un tableau pivot avec VBA:

Configuration de la table pivot

 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 

L'exécution de ce script a filtré PivotTable1 selon MyNames:

résultat