excelexcel-2016

excel countif entire row in a table


I have a structured table in excel 2016.

I want to have a cell to count the number of cells across the entire row within the table if it matches my criteria.

I have tried putting this formula in column A on each row =COUNTIF(Table[@],"my criteria") but that does not count properly.

However, this works: =COUNTIF(Table[@[ColB]:[ColH]],"my criteria"). But since my table will expand, I don't want to specify the column name [ColB], I want to refer to the entre row in the table.

A header countif colC colD colE
First formula A C
Second formula B C

formula = =COUNTIF(Table[@],"A") does not work

formula = =COUNTIF(Table[@[colC]:[colE]],"A") works

My table will expand both horizontally and vertically.


Solution

  • Please Note: This solution is only available if you chose to use VBA. VBA does not work in web versions of Excel. Please ensure that you resave your workbook as a macro-enabled workbook before proceeding.

    You can choose to use VBA and create your own custom worksheet formula. Since this question didn't start out as a VBA issue, I will be a bit more detailed on the process of setting this up as opposed to just throwing you some code and you having to figure out what to do with it.

    1. After you've re-saved your workbook as a macro-enabled workbook, open the VBA Editor (VBE) by pressing Alt and F11 simultaneously.
    2. In the VBE, click Insert > Module. You should now see Module1 highlighted on the left side bar (The project Explorer).
    3. Copy and paste the following code in the blank area of the module:
    Option Explicit
    
    Public Function GetMyRowCount(Criteria As Variant) As Long
    
        Dim ws As Worksheet
        Dim tblRng As Range, RowRng As Range
        With Application.Caller
            Set ws = .Worksheet
            Set tblRng = ws.Range(.ListObject.Name)
            Set RowRng = ws.Range(ws.Cells(.Row, .Column + 1), ws.Cells(.Row, tblRng.Columns.Count))
        End With
        
        GetMyRowCount = Application.WorksheetFunction.CountIf(RowRng, Criteria)
    
    End Function
    
    1. Now use this UDF (User Designed Function) in your worksheet. In the column you would like the calculation to be in, simply type =GetMyRowCount("My Criteria") and it should calculate.

    To point out how this code works in more detail:

    Using the information we obtained from bullets 2 and 3, we can establish the entire range of the lookup we need, and then place this range into your CountIf() function, along with the criteria you passed with the function's argument:

    GetMyRowCount = Application.WorksheetFunction.CountIf(RowRng, Criteria)
    

    As you can see in the following example, I wanted to count the number of times in the row the number 1 occurred:

    enter image description here

    Another example showing it works with text as well by using "Apple" as the criteria:

    enter image description here