Countif and excel vba

The COUNTIF function allows you to count the number of cells that meet a specific condition. It’s one of Excel’s most useful functions for data calculations and analysis. This blog post will show you how to use COUNTIF Excel VBA and provide some examples. Read on for all the details!

Excel VBA: COUNTIF function

COUNTIF is a function that counts the number of cells based on the criteria you specify. It combines COUNT and IF, and allows you to put in one criterion when doing the count. You can use this function, for example, to quickly get the number of products in a particular category, to find how many students scored higher than 80, and so on.  

You can simply use COUNTIF in a cell’s formula by entering =COUNTIF(range, criteria). We have a helpful article that explains how to use Excel COUNTIF in a worksheet — so if you ever need a refresher, just give it a read!

In some cases, however, you may need to write VBA COUNTIF function as a part of automation tasks in Excel. Let’s say, every day, you need to automatically import data from multiple external sources, process the data, summarize it using COUNTIF and other statistical functions, and finally send a report in PDF or Powerpoint. Automating that process using VBA is a great way to improve productivity and save time!

Tip: As a shortcut for getting data from multiple different sources into Excel, use an integration tool like Coupler.io. With Coupler.io’s powerful integration with Excel, you can easily import data from Airtable, Jira, Xero, plus many more into Excel on the schedule you want! The process happens automatically without any coding on your part! So, this can be an additional great time saver for you.

Figure 1.1. Coupler.io is a solution to import data to Google Sheets Excel or BigQuery from different sources

VBA COUNTIF syntax and parameters

COUNTIF is an Excel worksheet function. To write this function in VBA, specify the function name prefixed by WorksheetFunction, as follows:

Figure 2.1. VBA COUNTIF syntax

As you can see in the above image, COUNTIF returns Double and has two required arguments:

Name Data type Description
Arg1 Range Range. The range of cells to count.
Arg2 Variant Criterion. The criterion that defines which cells will be counted. It can be a number, text, expression, or cell reference.
For example: 85, “red”, “<=50”, or D8.

You can use the wildcard characters (? and *) in COUNTIF for more flexible criteria. This can be helpful if you want to do partial matching. For example:

  • If you want to count all cells that contain the word “Jade” or “Jane,” you can use “Ja?e” as the criteria. A question mark matches any single character.
  • If you want to count all cells that contain the word “Jake”, “James”, or “Jaqueline”, use “Ja*” as the criteria. An asterisk matches any sequence of characters.
  • If you want to count all cells that contain “90” or “90*”, use “90~*” as the criteria. A tilde (~) followed by a wildcard character matches the character.

COUNTIF VBA Excel: Download an example file

You can download the following Excel file to follow along with the examples in this article: 

Excel VBA CountIf.xlsx

The file contains a list of students and their scores on a Math exam. After adding VBA codes, save it as a macro-enabled workbook (.xlsm).

How to use COUNTIF in VBA: A basic example 

With the following student data, suppose you want to find how many students have passed vs. failed the math exam. 

Figure 4.1. How to use COUNTIF in VBA Example data

The following steps show you how to create a Sub procedure (macro) in VBA to get the result using VBA Excel COUNTIF:

  1. Press Alt+11 to open the Visual Basic Editor (VBE). Alternatively, you can open the VBE by clicking the Visual Basic button on the Developer tab.

Figure 4.2. The VBE

  1. On the menu, click Insert > Module.

Figure 4.3. Inserting a new VBA Module

  1. To get how many students passed the exam, type the following Sub in Module 1. The code counts the cells in the range D2:D21 if the value equals PASS. Then, it outputs the result in F3.
Sub CountStudentsPassedTheMathExam()
    Range("F3") = WorksheetFunction.CountIf(Range("D2:D21"), "PASS")
End Sub

Figure 4.4. COUNTIF VBA Count the number of students who passed the exam

  1. Run the Sub by pressing F5. Then, check your worksheet — in cell F3, you should see the result:

Figure 4.5. COUNTIF VBA The number of students who passed the exam

  1. Now, add the following Sub in the module to get the number of students who failed their math exam. The code counts the cells in range D2:D21 if the value equals FAIL. It outputs the result in G3.
Sub CountStudentsFailedTheMathExam()
    Range("G3") = WorksheetFunction.CountIf(Range("D2:D21"), "FAIL")
End Sub

Figure 4.6. COUNTIF VBA Count the number of students who failed the exam

  1. Run the code again by pressing F5, then check your worksheet. In cell G3, you should see the result:

Figure 4.7. COUNTIF VBA The number of students who passed the exam

As you can see, the results of both Subs in F3 and G3 are values, not formulas. This makes the results not change if any of the values in range D2:D21 change. If you’d like to see formulas in the cells, you can write the code slightly differently, as shown in the below Subs:

Sub CountStudentsPassedTheMathExam2()
    Range("F3") = "=COUNTIF(D2:D21,""PASS"")"
End Sub

Sub CountStudentsFailedTheMathExam2()
    Range("G3") = "=COUNTIF(D2:D21,""FAIL"")"
End Sub

Here’s an example result in F3:

Figure 4.8. Applying COUNTIF formulas using VBA code

COUNTIF function VBA: More examples

There are many ways to use COUNTIF VBA Excel. We’ll take a look at examples with operators, wildcards, multiple criteria, and more. 

COUNTIF VBA example #1: Using operators 

Operators (such as >, >=, <, <=, and <>) can be used in COUNTIF’s criteria. For example, you can use the “>” operator to only count cells that are higher than a certain value.

The following COUNTIF VBA code counts the number of students who got a score higher than 85:

Sub CountIfScoreHigherThan85()
    Dim rng As Range
    Dim criteria As Variant
    Dim result As Double
    
    Set rng = Range("C2:C21")
    criteria = "85"
    
    result = WorksheetFunction.CountIf(rng, ">" & criteria)
    
    MsgBox "There are " & result & " students who got a score higher than " & criteria & "."
End Sub

The code above uses three variables with different data types. First is rng, which stores the range of cells to count. The second is criteria, which holds the criteria we want to specify. The last is result, which stores the output of the COUNTIF function.

In this case, we are counting the cells in the range C2:C21 where its value is higher than 85. We use the “>” operator and combine it with the criteria using an ampersand symbol. The calculation result is stored in the result variable. Finally, the code outputs a message box showing the result:

Figure 5.1. COUNTIF VBA example operator

COUNTIF VBA example #2: Using wildcards for partial matching

The following COUNTIF in VBA counts the students who use Yahoo emails: 

Sub CountIfEmailIsYahoo()
    Dim rng As Range
    Dim criteria As Variant
    Dim result As Double
   
    Set rng = Range("B2:B21")
    criteria = "Yahoo"
   
    result = WorksheetFunction.CountIf(rng, "*" & criteria & "*")
   
    MsgBox "There are " & result & " students who use a " & criteria & " email."
End Sub

The function uses the “*” symbol at the beginning and end of the criteria to match all emails containing a Yahoo address. Notice that the criteria are not case-sensitive.

Here’s the output:

Figure 5.2. COUNTIF VBA example using a wildcard character for partial matching

COUNTIF VBA example #3: Multiple OR criteria

You can use multiple COUNTIFs (COUNTIF+COUNTIF+…) for multiple OR criteria in one column. For example, you could use COUNTIFs to count the number of cells that contain “red” OR “blue.”

With our student dataset, you can use the following code to see how many students got scores higher than 95 OR lower than 25:

Sub CountIfMultipleOrCriteria()
    Dim rng As Range
    Dim criteria1, criteria2 As Variant
    Dim result As Double
   
    Set rng = Range("C2:C21")
    criteria1 = 95
    criteria2 = 25
   
    result = WorksheetFunction.CountIf(rng, ">" & criteria1) _
                + WorksheetFunction.CountIf(rng, "<" & criteria2)
   
    MsgBox result & " students got a score higher than " & criteria1 & " OR lower than " & criteria2
End Sub

The solution is simple and straightforward. You can just use multiple COUNTIFs if you have more than one OR criteria in a single column.

Here’s the output of the above code:

Figure 5.3. COUNTIF VBA example multiple OR criteria

COUNTIF VBA example #4: Multiple AND criteria

Suppose you need to count the number of students who use Yahoo email AND have a math score higher than 90. COUNTIF does not work in this case.

The COUNTIFS function might be the solution you’re looking for. You can also get the result manually using a loop, but we recommend you use COUNTIFS if possible.

Code 1: Using COUNTIFS

In the code below, we use the COUNTIFS function with 4 parameters: 2 range and 2 criteria parameters.

Sub CountIfsMultipleAndCriteria()
    Dim rng1, rng2 As Range
    Dim criteria1, criteria2 As Variant
    Dim result As Double
   
    Set rng1 = Range("B2:B21")
    criteria1 = "Yahoo"
   
    Set rng2 = Range("C2:C21")
    criteria2 = 90
   
    result = WorksheetFunction.CountIfs(rng1, "*" & criteria1 & "*", rng2, ">" & criteria2)
   
    MsgBox "Total students who use " & criteria1 & _
        " AND have a score higher than " & criteria2 & " is " & result
End Sub

Here’s the output:

Figure 5.4. COUNTIFS VBA example multiple AND criteria

Code 2: Manually count in a loop

The below code loops from Row 2 to 21 and checks all values in Column B and Column C. If there is a match, the result variable is incremented by 1. For Column B, the Like operator is used to find a partial match. Notice that it’s case-sensitive, so we apply LCase when making the comparison. 

Sub CountWithMultipleAndCriteria()
    Dim criteria1, criteria2 As Variant
    Dim result As Double
   
    criteria1 = "Yahoo"
    criteria2 = 90
    result = 0
   
    ' Loop each row
    For i = 2 To 22
        If LCase(Cells(i, "B")) Like LCase("*" & criteria1 & "*") _
          And Cells(i, "C") > criteria2 Then
            result = result + 1
        End If
    Next i
   
    MsgBox "Total students who use " & criteria1 & _
        " AND got a score higher than " & criteria2 & " = " & result
End Sub

There might be a time when you might want to do processing in a loop. For example, if you’re trying to count cells by checking if they’re bold or having certain colors, etc., which can’t be done using COUNTIFS alone. 

COUNTIF VBA example #5: Using COUNTIF to highlight duplicates

There are times when you have large amounts of data with duplicates. Instead of using the Remove Duplicates command on the Data tab, you might want to just mark them for future reference. This is a pretty useful option when you’re doing data analysis.

See the below code that uses Excel VBA COUNTIF to mark the duplicates with red color. The checking is based on Column A which contains student names. It leaves the first unique values unmarked.

Sub HighlightDuplicates()
    With Range("A2:D23")
        .Select
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:="=COUNTIF($A$2:$A2,$A2)>1"
        .FormatConditions(1).Font.Color = RGB(255, 0, 0)
    End With
End Sub

If you insert two duplicates and run the above code, you’ll see a result similar to this below—duplicates are marked in red color:

Figure 5.5. COUNTIF VBA example data with duplicates

COUNTIF in VBA Excel – Summary

With Excel VBA, you can use the COUNTIF function to tally up numbers based on the criteria you set. After reading this article, hopefully, you can easily use this function in VBA code for things like data analysis and calculations.

If you’re looking for a solution to import data from various sources into Excel without having to code any VBA code, consider using Coupler.io. You can also use it to automate your reporting process by scheduling the imports. Check out our website for more information about how Coupler.io can help you take your data analysis to the next level.

Thanks for reading, and happy COUNTing!

  • Fitrianingrum Seto

    Senior analyst programmer

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Подсчет количества ячеек в диапазоне, соответствующих заданным критериям, методами CountIf и CountIfs объекта WorksheetFunction из кода VBA Excel.

Metod WorksheetFunction.CountIf

Определение

Определение метода CountIf объекта WorksheetFunction в VBA Excel:

WorksheetFunction.CountIf  — это метод, который подсчитывает в указанном диапазоне количество ячеек, соответствующих одному заданному критерию (условию), и возвращает значение типа Double.

Синтаксис

Синтаксис метода CountIf объекта WorksheetFunction:

WorksheetFunction.CountIf(Arg1, Arg2)

Параметры

Параметры метода CountIf объекта WorksheetFunction:

Параметр Описание
Arg1 Диапазон, в котором необходимо подсчитать количество ячеек, соответствующих заданному критерию. Тип данных — Range.
Arg2 Критерий в виде числа, текста, выражения или ссылки на ячейку, определяющий, какие ячейки будут засчитываться. Тип данных — Variant.

Примечания

  • Метод WorksheetFunction.CountIf позволяет получить количество ячеек, соответствующих заданному критерию, в указанном диапазоне.
  • Примеры критериев (условий): 25, "25", ">50", "<50", "береза" или D5.
  • В критериях можно использовать знаки подстановки (спецсимволы): знак вопроса (?) и звездочку (*). Знак вопроса заменяет один любой символ, а звездочка соответствует любой последовательности символов. Чтобы знак вопроса (?) и звездочка (*) обозначали сами себя, перед ними указывается тильда (~).

Metod WorksheetFunction.CountIfs

Должен отметить, что у меня в VBA Excel 2016 метод WorksheetFunction.CountIfs не работает. При попытке применить данный метод, генерируется ошибка:

Run-time error '1004':
Невозможно получить свойство CountIfs класса WorksheetFunction

Очевидно, метод WorksheetFunction.CountIfs предусмотрен для более новых версий VBA Excel. Статья на сайте разработчиков датирована 2021 годом.

Определение

Определение метода CountIfs объекта WorksheetFunction в VBA Excel:

WorksheetFunction.CountIfs  — это метод, который подсчитывает в указанном диапазоне количество ячеек, соответствующих одному или нескольким заданным критериям (условиям), и возвращает значение типа Double.

Синтаксис

Синтаксис метода CountIfs объекта WorksheetFunction:

WorksheetFunction.CountIfs(Arg1, Arg2, ..., Arg30)

Параметры

Параметры метода CountIfs объекта WorksheetFunction:

Параметр Описание
Arg1 Диапазон, в котором необходимо подсчитать количество ячеек, соответствующих заданным критериям. Тип данных — Range.
Arg2-Arg30 Один или несколько критериев в виде числа, текста, выражения или ссылки на ячейку, определяющие, какие ячейки будут засчитываться. Тип данных — Variant.

Примечания

  • Метод WorksheetFunction.CountIfs позволяет получить количество ячеек, соответствующих одному или нескольким заданным критериям, в указанном диапазоне.
  • Значение пустой ячейки рассматривается как 0.
  • Примеры критериев (условий): 25, "25", ">50", "<50", "береза" или D5.
  • В критериях можно использовать знаки подстановки (спецсимволы): знак вопроса (?) и звездочку (*). Знак вопроса заменяет один любой символ, а звездочка соответствует любой последовательности символов. Чтобы знак вопроса (?) и звездочка (*) обозначали сами себя, перед ними указывается тильда (~).

Примеры с WorksheetFunction.CountIf

Таблица, на которой тестировались примеры:

Sub Primer()

Dim n As Double

    n = WorksheetFunction.CountIf(Range(«A1:D11»), «<5»)

MsgBox n  ‘Результат: 4

    n = WorksheetFunction.CountIf(Range(«A1:D11»), «>=4500»)

MsgBox n  ‘Результат: 5

    n = WorksheetFunction.CountIf(Range(«A1:D11»), «1600×720»)

MsgBox n  ‘Результат: 4

    n = WorksheetFunction.CountIf(Range(«A1:D11»), «Nokia*»)

MsgBox n  ‘Результат: 2

End Sub

Предыдущая статья по этой теме: VBA Excel. Методы Count, CountA и CountBlank.


title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.CountIf method (Excel)

vbaxl10.chm137242

vbaxl10.chm137242

excel

Excel.WorksheetFunction.CountIf

d0251b63-cc9e-a58c-1862-adbd58004126

05/22/2019

medium

WorksheetFunction.CountIf method (Excel)

Counts the number of cells within a range that meet the given criteria.

Syntax

expression.CountIf (Arg1, Arg2)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required Range The range of cells from which you want to count cells.
Arg2 Required Variant The criteria in the form of a number, expression, cell reference, or text that defines which cells will be counted. For example, criteria can be expressed as 32, «32», «>32», «apples», or B4.

Return value

Double

Remarks

Use the wildcard characters, question mark (?) and asterisk (*), for the criteria. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character.

[!includeSupport and feedback]

The Excel COUNTIF function returns the number of cells in a range that meet a specified criteria

Example: Excel COUNTIF Function

Excel COUNTIF Function

METHOD 1. Excel COUNTIF Function using hardcoded values

EXCEL

Result in cell E8 (1) — returns the number of cells that are equal to 500 in range (C8:C14).

Result in cell E9 (3) — returns the number of cells that are greater than 500 in range (C8:C14).

Result in cell E10 (3) — returns the number of cells that are less than 500 in range (C8:C14).

Result in cell E11 (4) — returns the number of cells that are less than or equal to 500 in range (C8:C14).

Result in cell E12 (4) — returns the number of cells that are greater than or equal to 500 in range (C8:C14).

METHOD 2. Excel COUNTIF Function using links

EXCEL

Result in cell E8 (1) — returns the number of cells that are equal to the same value as in cell (C5) in range (C8:C14).

Result in cell E9 (3) — returns the number of cells that are greater than the value in cell (C5) in range (C8:C14).

Result in cell E10 (3) — returns the number of cells that are less than the value in cell (C5) in range (C8:C14).

Result in cell E11 (4) — returns the number of cells that are less than or equal to the value in cell (C5) in range (C8:C14).

Result in cell E12 (4) — returns the number of cells that are greater than or equal to the value in cell (C5) in range (C8:C14).

METHOD 3. Excel COUNTIF function using the Excel built-in function library with hardcoded value

EXCEL

Formulas tab > Function Library group > More Functions > Statistical > COUNTIF > populate the input boxes

=COUNTIF(C8:C14,»>500″)
Note: in this example we are populating both of the input boxes, as they are both required COUNTIF arguments, with a criteria of greater than 500.
Built-in Excel COUNTIF Function using hardocded values

METHOD 4. Excel COUNTIF function using the Excel built-in function library with links

EXCEL

Formulas tab > Function Library group > More Functions > Statistical > COUNTIF > populate the input boxes

=COUNTIF(C8:C14,»>»&C5)
Note: in this example we are populating both of the input boxes, as they are both required COUNTIF arguments, with a criteria of greater than the value in cell (C5).
Built-in Excel COUNTIF Function using links

METHOD 1. Excel COUNTIF function using VBA with hardcoded values

VBA

Sub Excel_COUNTIF_Function()

‘declare a variable
Dim ws As Worksheet

Set ws = Worksheets(«COUNTIF»)

‘apply the Excel COUNTIF function
ws.Range(«E8») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), 500)
ws.Range(«E9») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «>500»)
ws.Range(«E10») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «<500»)
ws.Range(«E11») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «<=500»)
ws.Range(«E12») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «>=500»)

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named COUNTIF.
Data Range: Ensure that the data that you want to count from is captured in range («C8:C14») in the COUNTIF worksheet.

ADJUSTABLE PARAMETERS
Data Range: Select the range that you want to count from by changing the range («C8:C14») to any range in the worksheet that doesn’t conflict with the formula.
Output Range: Select the output range by changing the cell references («E8»), («E9»), («E10»), («E11») and («E12») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.

METHOD 2. Excel COUNTIF function using VBA with links

VBA

Sub Excel_COUNTIF_Function()

‘declare a variable
Dim ws As Worksheet

Set ws = Worksheets(«COUNTIF»)

‘apply the Excel COUNTIF function
ws.Range(«E8») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), ws.Range(«C5»))
ws.Range(«E9») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «>» & ws.Range(«C5»))
ws.Range(«E10») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «<» & ws.Range(«C5»))
ws.Range(«E11») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «<=» & ws.Range(«C5»))
ws.Range(«E12») = Application.WorksheetFunction.CountIf(ws.Range(«C8:C14»), «>=» & ws.Range(«C5»))

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named COUNTIF.
Data Range: Ensure that the data that you want to count from is captured in range («C8:C14») in the COUNTIF worksheet.
Specific Value: Input the specific value that you want to test for in cell («C5») in the COUNTIF worksheet.

ADJUSTABLE PARAMETERS
Specific Value: Select the specific value that you want to test for by changing the value in cell («C5»).
Data Range: Select the range that you want to count from by changing the range («C8:C14») to any range in the worksheet that doesn’t conflict with the formula.
Output Range: Select the output range by changing the Range references («E8»), («E9»), («E10»), («E11») and («E12») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.

Usage of the Excel COUNTIF function and formula syntax

EXPLANATION

DESCRIPTION
The Excel COUNTIF function returns the number of cells in a range that meet a specified criteria.

SYNTAX
=COUNTIF(range, criteria)

ARGUMENTS
range: (Required) The range of cells you want to count from.
criteria: (Required) The criteria that is used to determine which of the cells from the specified range should be counted.

Like this post? Please share to your friends:
  • Countif and countifs functions in excel
  • Countif and countifs function in excel
  • Countbycolor excel на русском
  • Countblank excel на русском
  • Countable uncountable word wall