Excel阵列过滤器

时间:2018-05-20 19:57:13

标签: vba excel-vba excel-2016 excel

我在Excel中有四列数据。第三列(" C")包含一个具有国家名称的字符串,例如"该国家的名称是中国"。字符串不标准化,因此我无法使用左/右/中等字符串函数。我正在创建一个宏来过滤六个国家(埃及,美国,中国,俄罗斯,日本和乌干达)。到目前为止,我可以使用以下宏来获得两个国家:

Sub Countries ()
   Activesheet.Range("A1:D1000").Autofilter Field:=3, Criteria1:=Array("*Japan*","*China*"),Operator:=xlFilterValues
End Sub

这是有效的,我可以将这两个国家过滤掉。但是,当我添加更多国家/地区时,Excel不会显示国家/地区并且不返回任何行。 我不确定我做得对不对,我希望有人可以帮助我

1 个答案:

答案 0 :(得分:0)

你可以遍历各个国家:

Option Explicit

Sub main()
    Dim filter As Variant
    Dim countriesRng As Range

    Set countriesRng = Range("A1") ' initial dummy range to use Union() without checking for 'countriesRng' being 'Nothing'
    With Range("A1:D" & cells(Rows.Count, "C").End(xlUp).row) ' reference columns A:D from row 1 down to column C last not empty row
        For Each filter In Array("Egypt", "USA", "China", "Russia", "Japan", "Uganda") ' loop through countries
            .AutoFilter Field:=3, Criteria1:="*" & filter & "*" ' filter current country
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then Set countriesRng = Union(countriesRng, .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible)) ' if any filtered cells other than header then add them to 'countriesRng'
        Next
       .parent.AutoFilterMode = False

        Set countriesRng = Intersect(countriesRng, Range("C:C")) ' get rid of the initial dummy range
        If Not countriesRng Is Nothing Then ' if any filtered country
            .Resize(.Rows.Count - 1).Offset(1).EntireRow.Hidden = True ' hide all records
            countriesRng.EntireRow.Hidden = False ' unhide ones with filtered countries
        End If
    End With
End Sub