2013-05-17 20 views
5

In questo momento sto facendo la codifica per impostare un filtro per un grafico di dati. In sostanza, non so come inviare la scheda tecnica qui quindi basta provare a digitare loro):Imposta il filtro automatico con più caratteri jolly

(partendo da sinistra è colonna A) Nome * BDevice * Quantità * Vendite * Proprietario

Fondamentalmente ho bisogno di filtrare per 2 colonne: -Il dispositivo BDevice con qualsiasi parola contiene "M1454" o "M1467" o "M1879" (Significa che M1454A o M1467TR si adatterebbero ancora) -Il proprietario con PROD o RISK

Ecco il codice che ho scritto:

Sub AutoFilter() 

    ActiveWorkbook.ActiveSheet..Range(B:B).Select 

    Selection.Autofilter Field:=1 Criteria1:=Array(_ 
     "*M1454*", "*M1467*", "*M1879*"), Operator:=xlFilterValues 

    Selection.AutoFilter Field:=4 Criteria1:="=PROD" _ 
     , Operator:=xlOr, Criteria2:="=RISK" 

End Sub 

Quando eseguo il codice, la macchina restituisce l'errore 1004 e la parte che sembra essere errata è la parte filtro 2 (non sono sicuro dell'uso di Field, quindi non posso dirlo con certezza)

Modifica; Santosh: Quando provo il tuo codice, la macchina ottiene l'errore 9 indice fuori intervallo. L'errore è venuto dalla dichiarazione con. (Dal momento che la tabella dei dati ha dalla A alla colonna come quindi ho solo cambiare A: AS)

+0

Puoi farmi sapere il nome del foglio su cui si trovano i tuoi dati? – Santosh

+3

AutoFilter è un termine VBA incorporato. Ciò causa un errore di compilazione sulla mia macchina quando eseguo il codice da @Santosh all'interno dell'oggetto foglio. Rinominare il Sub risolve questo problema. – Mike

risposta

0

Prova sottostante Codice:

max 2 espressione jolly per Criteria1 funziona. Segnalare questo link

Sub AutoFilter() 

    With ThisWorkbook.Sheets("sheet1").Range("A:E") 
     .AutoFilter Field:=2, Criteria1:=Array("*M1454*", "*M1467*"), Operator:=xlFilterValues 
     .AutoFilter Field:=5, Criteria1:="=PROD", Operator:=xlOr, Criteria2:="=RISK" 
    End With 

End Sub 
6

Mentre v'è un massimo di due wildcard diretti per campo nel AutoFilter method, pattern matching può essere usato per creare una matrice che sostituisce i caratteri jolly con il operatore: = xlFilterValues ​​ opzione. A Select Case statement aiuta la corrispondenza dei caratteri jolly.

Il secondo campo è un semplice criterio 1 e criterio 2 corrispondono direttamente a un operatore : = xlOr che unisce i due criteri.

Sub multiWildcardFilter() 
    Dim a As Long, aARRs As Variant, dVALs As Object 

    Set dVALs = CreateObject("Scripting.Dictionary") 
    dVALs.CompareMode = vbTextCompare 

    With Worksheets("Sheet1") 
     If .AutoFilterMode Then .AutoFilterMode = False 
     With .Cells(1, 1).CurrentRegion 
      'build a dictionary so the keys can be used as the array filter 
      aARRs = .Columns(2).Cells.Value2 
      For a = LBound(aARRs, 1) + 1 To UBound(aARRs, 1) 
       Select Case True 
        Case aARRs(a, 1) Like "MK1454*" 
         dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1) 
        Case aARRs(a, 1) Like "MK1467*" 
         dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1) 
        Case aARRs(a, 1) Like "MK1879*" 
         dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1) 
        Case Else 
         'no match. do nothing 
       End Select 
      Next a 

      'filter on column B if dictionary keys exist 
      If CBool(dVALs.Count) Then _ 
       .AutoFilter Field:=2, Criteria1:=dVALs.keys, _ 
             Operator:=xlFilterValues, VisibleDropDown:=False 
      'filter on column E 
      .AutoFilter Field:=5, Criteria1:="PROD", Operator:=xlOr, _ 
            Criteria2:="RISK", VisibleDropDown:=False 

      'data is filtered on MK1454*, MK1467* or MK1879* (column B) 
      'column E is either PROD or RISK 
      'Perform work on filtered data here 
     End With 
     If .AutoFilterMode Then .AutoFilterMode = False 
    End With 

    dVALs.RemoveAll: Set dVALs = Nothing 
End Sub 

Se exclusions¹ sono da aggiungere al filtraggio, la loro logica deve essere posto nella parte superiore del Select .. End Select in modo che essi non vengono aggiunti attraverso un falso positivo per altri coincidenti.

multi_Wildcard_Filter_Before
Prima di applicare il filtro automatico Metodo

multi_Wildcard_Filter_After
Dopo aver applicato il filtro automatico w/multiple jolly


¹ Vedi Can Advanced Filter criteria be in the VBA rather than a range? e Can AutoFilter take both inclusive and non-inclusive wildcards from Dictionary keys? per più sull'aggiunta di esclusioni al set di filtri del dizionario.

1

Per utilizzare stringhe parziali per escludere le righe e comprendono spazi vuoti si dovrebbe usare

'From Jeeped's code 
Dim dVals As Scripting.Dictionary 
Set dVals = CreateObject("Scripting.Dictionary") 
dVals.CompareMode = vbTextCompare  


Dim col3() As Variant 
Dim col3init As Integer 

'Swallow row3 into an array; start from 1 so it corresponds to row 
For col3init = 1 to Sheets("Sheet1").UsedRange.Rows.count 
    col3(col3init) = Sheets("Sheet1").Range(Cells(col3init,3),Cells(col3init,3)).Value 
Next col3init 

Dim excludeArray() As Variant 
'Partial strings in below array will be checked against rows 
excludeArray = Array("MK1", "MK2", "MK3") 

Dim col3check As Integer 
Dim excludecheck as Integer 
Dim violations As Integer 
For col3check = 1 to UBound(col3) 
    For excludecheck = 0 to UBound(excludeArray) 
     If Instr(1,col3(col3check),excludeArray(excludecheck)) <> 0 Then 
      violations = violations + 1 
      'Sometimes the partial string you're filtering out for may appear more than once. 
     End If 
    Next col3check 

    If violations = 0 and Not dVals.Exists(col3(col3check)) Then 
     dVals.Add Key:=col3(col3check), Item:=col3(col3check) 'adds keys for items where the partial strings in excludeArray do NOT appear 
    ElseIf col3(col3check) = "" Then 
     dVals.Item(Chr(61)) = Chr(61) 'blanks 
    End If 
    violations = 0 
Next col3check  

I dVals.Item (Chr (61)) = Chr (61) l'idea viene dall'altra risposta di Jeeped qui Multiple Filter Criteria for blanks and numbers using wildcard on same field just doesn't work

Problemi correlati