2
votes

I have data in four columns in Excel. Column three ("C") contains a string which has a country name, e.g "The name of the country is China". The string is not standardized hence I am unable to use string functions like left/right/mid. I am creating a macro to filter six countries (Egypt, USA, China, Russia, Japan and Uganda). So far I can get two countries using the following macro:

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

This is working and I am able to get the two countries filtered. However when I add more countries the Excel does not bring up the countries and returns no rows. I am not sure what I am not doing right and I am hoping someone can help me please

1
What is your code where you add more countries?JohnyL
@JohnyL the code is a continuation in the array, like: Array("Japan","China","USA","Russia","Egypt",.....)....Lex
Interesting question. Doesn't seem to like more than 2 wildcarded items and if you add a third non wildcarded item it selects only that.QHarr
This may be of interest to you stackoverflow.com/questions/16602872/… Apparently maximum of two direct wildcards per field in the AutoFilter methodQHarr

1 Answers

0
votes

you could loop through countries:

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