Excel 数组过滤器

Excel Array Filter

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

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

这很有效,我能够过滤这两个国家。但是,当我添加更多国家/地区时,Excel 不会显示这些国家/地区并且 returns 不会显示任何行。 我不确定我做错了什么,我希望有人能帮助我

你可以遍历国家:

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