Auto filter with more than 2 criteria with wildcards

老子叫甜甜 提交于 2021-02-08 08:10:42

问题


I'm using the following code in a Macro:

Sub Macro2()
    Sheets("Bill").Select
    Range("A2:AA2").Select
    Rows("2:2").Select
    Selection.AutoFilter
    Range("T2").Select
    ActiveSheet.Range("$A$2:$AA$111").AutoFilter Field:=20, Criteria1:=Array("=*Base ch*", _
    "=*Service*", "=*Supply Ch*", "=*Customer*", "=*Analyst*"), Operator:=xlFilterValues
End Sub

It's not showing any error and when I use only 2 criteria It works perfect. The issue is when I try more than 2. It doesn't show anything.

I tried the operator OR but I think that only works with 2 criteria.

Any suggestions?


回答1:


Instead of AutoFilter, try Advanced Filter when dealing with multiple wildcard criteria. All you need is to either have a sheet with those criteria listed along with wildcard or create the criteria sheet programmatically and delete it in the end.

The below code will create a criteria sheet programmatically and list all your criteria in column A starting from Row2 and A1 on criteria sheet will contain the column header from your data sheet.

Sub FilterWithMultipleWildcardCriteria()
Dim ws As Worksheet, wsCriteria As Worksheet
Dim strCriterai
Dim lr As Long

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set ws = Sheets("Bill")
If ws.FilterMode Then ws.ShowAllData
lr = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

On Error Resume Next
Set wsCriteria = Sheets("Criteria")
wsCriteria.Cells.Clear
On Error GoTo 0

If wsCriteria Is Nothing Then
    Set wsCriteria = Sheets.Add
    wsCriteria.Name = "Criteria"
End If

wsCriteria.Range("A1").Value = ws.Range("T2").Value
strcriteria = Array("*Base ch*", "*Service*", "*Supply Ch*", "*Customer*", "*Analyst*")

wsCriteria.Range("A2").Resize(UBound(strcriteria) + 1).Value = Application.Transpose(strcriteria)

ws.Range("A2:AA" & lr).AdvancedFilter xlFilterInPlace, wsCriteria.Range("A1").CurrentRegion

wsCriteria.Delete

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub


来源:https://stackoverflow.com/questions/49858980/auto-filter-with-more-than-2-criteria-with-wildcards

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!