excelvbaautofilter

Excel VBA - autofilter by text


I need to figure out, how to filter by one particular name. I have two names tichava and tichaval. I want to filter out just the tichava one, problem is, that in some cases both names are in the same column, like this enter image description here

see the yellow parts. I am counting number of visible rows after the filtering is done. Problem is, that if I filter by tichava I also get tichaval if I do just equal to tichava, only the ones that are simply tichava are shown, which is wrong. What should I do? Do I need to create an Array("tichava", ", tichava", "tichava,") and filter it like this? Is there no other option?


Solution

  • As you tagged the question VBA, I assume that a small VBA function is okay.

    Now defining the filter in VBA has exactly the possibilities that you have when using auto filter in Excel itself - select one or more values you want to select or use advanced filters to define one or two "wildcard" (but not more that two) filters, eg contains or starts with. I don't see a way to specify an advanced filter for your exact needs.

    First define a simple function

    Public Function containsName(haystack As String, needle As String) As Boolean
        Dim words() As String, i As Long
        words = Split(Replace(haystack, " ", ""), ",")
        For i = 0 To UBound(words)
            If words(i) = needle Then
                containsName = True
                Exit Function
            End If
        Next i
    End Function
    

    Now this function will return True if the string contains exactly the name you are looking for. With this, you have two possibilities:

    Either you use a helper column in Excel, use the function as UDF in a formula, eg =containsName(T2, "tichava") and filter your data by this column.

    Or, if a helper column is not an option, loop over all data and create an array of all cells that you want to include and use that array as filter.