Подсчет количества ячеек в диапазоне, соответствующих заданным критериям, методами 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.
In this Article
- COUNTIF WorksheetFunction
- Assigning a COUNTIF result to a Variable
- Using COUNTIFS
- Using COUNTIF with a Range Object
- Using COUNTIFS on Multiple Range Objects
- COUNTIF Formula
- Formula Method
- FormulaR1C1 Method
This tutorial will show you how to use the Excel COUNTIF and COUNTIFS functions in VBA
VBA does not have an equivalent of Excel’s COUNTIF or COUNTIFS Functions. Instead, you must call the Excel functions by using the WorkSheetFunction object.
COUNTIF WorksheetFunction
The WorksheetFunction object can be used to call most of the Excel functions that are available within the Insert Function dialog box in Excel. The COUNTIF Function is one of them.
Sub TestCountIf()
Range("D10") = Application.WorksheetFunction.CountIf(Range("D2:D9"), ">5")
End Sub
The procedure above will only count the cells in Range(D2:D9) if they have a value of 5 or greater. Notice that because you are using a greater than sign, the criteria greater than 5 needs to be within parenthesis.
Assigning a COUNTIF result to a Variable
You may want to use the result of your formula elsewhere in code rather than writing it directly back to an Excel Range. If this is the case, you can assign the result to a variable to use later in your code.
Sub AssignSumIfVariable()
Dim result as Double
'Assign the variable
result = Application.WorksheetFunction.CountIf(Range("D2:D9"), ">5")
'Show the result
MsgBox "The count of cells with a value greater than 5 is " & result
End Sub
Using COUNTIFS
The COUNTIFS function is similar to the COUNTIF WorksheetFunction but it enables you to check for more than one criteria. In the example below, the formula will count up the number of cells in D2 to D9 where the Sale Price is greater than 6 AND the Cost Price is greater than 5.
Sub UsingCountIfs()
Range("D10") = WorksheetFunction.CountIfs(Range("C2:C9"), ">6", Range("E2:E9"), ">5")
End Sub
Using COUNTIF with a Range Object
You can assign a group of cells to the Range object, and then use that Range object with the WorksheetFunction object.
Sub TestCountIFRange()
Dim rngCount as Range
'assign the range of cells
Set rngCount = Range("D2:D9")
'use the range in the formula
Range("D10") = WorksheetFunction.SUMIF(rngCount, ">5")
'release the range objects
Set rngCount = Nothing
End Sub
Using COUNTIFS on Multiple Range Objects
Similarly, you can use COUNTIFS on multiple Range Objects.
Sub TestCountMultipleRanges()
Dim rngCriteria1 As Range
Dim rngCriteria2 as Range
'assign the range of cells
Set rngCriteria1= Range("D2:D9")
Set rngCriteria2 = Range("E2:E10")
'use the ranges in the formula
Range("D10") = WorksheetFunction.CountIfs(rngCriteria1, ">6", rngCriteria2, ">5")
'release the range objects
Set rngCriteria1 = Nothing
Set rngCriteria2 = Nothing
End Sub
COUNTIF Formula
When you use the WorksheetFunction.COUNTIF to add a sum to a range in your worksheet, a static value is returned, not a flexible formula. This means that when your figures in Excel change, the value that has been returned by the WorksheetFunction will not change.
In the example above, the procedure has counted the amount of cells with values in Range(D2:D9) where the Sale Price is greater than 6, and the result was put in D10. As you can see in the formula bar, this result is a figure and not a formula.
If any of the values change in Range(D2:D9), the result in D10 will NOT change.
Instead of using the WorksheetFunction.SumIf, you can use VBA to apply a COUNTIF Function to a cell using the Formula or FormulaR1C1 methods.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Formula Method
The formula method allows you to point specifically to a range of cells eg: D2:D9 as shown below.
Sub TestCountIf()
Range("D10").FormulaR1C1 ="=COUNTIF(D2:D9, "">5"")"
End Sub
FormulaR1C1 Method
The FormulaR1C1 method is more flexible in that it does not restrict you to a set range of cells. The example below will give us the same answer as the one above.
Sub TestCountIf()
Range("D10").FormulaR1C1 = "=COUNTIF(R[-8]C:R[-1]C,"">5"")"
End Sub
However, to make the formula even more flexible, we could amend the code to look like this:
Sub TestCountIf()
ActiveCell.FormulaR1C1 = "=COUNTIF(R[-8]C:R[-1]C,"">5"")"
End Sub
Wherever you are in your worksheet, the formula will then count the cells that meet the criteria directly above it and place the answer into your ActiveCell. The Range inside the COUNTIF function has to be referred to using the Row (R) and Column (C) syntax.
Both these methods enable you to use Dynamic Excel formulas within VBA.
There will now be a formula in D10 instead of a value.
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.
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:
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.
The following steps show you how to create a Sub procedure (macro) in VBA to get the result using VBA Excel COUNTIF:
- 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.
- On the menu, click Insert > Module.
- 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
- Run the Sub by pressing F5. Then, check your worksheet — in cell F3, you should see the result:
- 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
- Run the code again by pressing F5, then check your worksheet. In cell G3, you should see the result:
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:
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:
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:
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:
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:
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:
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!
-
Senior analyst programmer
Back to Blog
Focus on your business
goals while we take care of your data!
Try Coupler.io
Содержание
- СЧЕТЕСЛИ Рабочий лист
- Присвоение переменной результата COUNTIF
- Использование СЧЁТЕСЛИМН
- Использование COUNTIF с объектом диапазона
- Использование COUNTIFS для объектов с несколькими диапазонами
- СЧЁТЕСЛИ Формула
Из этого туториала Вы узнаете, как использовать функции Excel СЧЁТЕСЛИ и СЧЁТЕСЛИ в VBA.
VBA не имеет эквивалента функций СЧЁТЕСЛИ или СЧЁТЕСЛИМН, которые вы можете использовать — пользователь должен использовать встроенные функции Excel в VBA, используя Рабочий лист объект.
СЧЕТЕСЛИ Рабочий лист
Объект WorksheetFunction можно использовать для вызова большинства функций Excel, доступных в диалоговом окне «Вставить функцию» в Excel. Функция СЧЁТЕСЛИ — одна из них.
123 | Sub TestCountIf ()Range («D10») = Application.WorksheetFunction.CountIf (Range («D2: D9»), «> 5»)Конец подписки |
Приведенная выше процедура будет подсчитывать только ячейки в диапазоне (D2: D9), если они имеют значение 5 или больше. Обратите внимание: поскольку вы используете знак «больше», критерии больше 5 должны быть заключены в круглые скобки.
Присвоение переменной результата COUNTIF
Возможно, вы захотите использовать результат своей формулы в другом месте кода, а не записывать его непосредственно обратно в Excel Range. В этом случае вы можете присвоить результат переменной, которая будет использоваться позже в вашем коде.
1234567 | Sub AssignSumIfVariable ()Тусклый результат как двойной’Назначьте переменнуюresult = Application.WorksheetFunction.CountIf (Range («D2: D9»), «> 5»)’Показать результатMsgBox «Количество ячеек со значением больше 5 равно» & результатКонец подписки |
Использование СЧЁТЕСЛИМН
Функция СЧЁТЕСЛИМН похожа на функцию СЧЁТЕСЛИ Worksheet, но позволяет вам проверять более одного критерия. В приведенном ниже примере формула подсчитывает количество ячеек от D2 до D9, где цена продажи больше 6, а себестоимость больше 5.
123 | Sub UsingCountIfs ()Range («D10») = WorksheetFunction.CountIfs (Range («C2: C9»), «> 6», Range («E2: E9»), «> 5»)Конец подписки |
Использование COUNTIF с объектом диапазона
Вы можете назначить группу ячеек объекту Range, а затем использовать этот объект Range с Рабочий лист объект.
123456789 | Sub TestCountIFRange ()Dim rngCount as Range’назначить диапазон ячеекУстановите rngCount = Range («D2: D9»)’используйте диапазон в формулеДиапазон («D10») = WorksheetFunction.SUMIF (rngCount, «> 5»)’освободить объекты диапазонаУстановите rngCount = NothingКонец подписки |
Использование COUNTIFS для объектов с несколькими диапазонами
Точно так же вы можете использовать COUNTIFS для нескольких объектов диапазона.
123456789101112 | Sub TestCountMultipleRanges ()Dim rngCriteria1 As ДиапазонDim rngCriteria2 as Range’назначить диапазон ячеекУстановить rngCriteria1 = Range («D2: D9»)Установить rngCriteria2 = Range («E2: E10»)’используйте диапазоны в формулеДиапазон («D10») = WorksheetFunction.CountIfs (rngCriteria1, «> 6», rngCriteria2, «> 5»)’освободить объекты диапазонаУстановить rngCriteria1 = NothingУстановить rngCriteria2 = NothingКонец подписки |
СЧЁТЕСЛИ Формула
Когда вы используете WorksheetFunction.COUNTIF чтобы добавить сумму к диапазону на листе, возвращается статическое значение, а не гибкая формула. Это означает, что при изменении ваших цифр в Excel значение, возвращаемое Рабочий лист не изменится.
В приведенном выше примере процедура подсчитала количество ячеек со значениями в диапазоне (D2: D9), где цена продажи больше 6, и результат был помещен в D10. Как вы можете видеть в строке формул, это число, а не формула.
Если любое из значений изменится в диапазоне (D2: D9), результат в D10 будет НЕТ изменение.
Вместо использования Рабочий лист Функция. Сумма Если, вы можете использовать VBA для применения функции СУММЕСЛИ к ячейке с помощью Формула или Формула R1C1 методы.
Формула Метод
Метод формулы позволяет указать конкретный диапазон ячеек, например: D2: D9, как показано ниже.
123 | Sub TestCountIf ()Диапазон («D10»). FormulaR1C1 = «= СЧЁТЕСЛИ (D2: D9,» «> 5» «)»Конец подписки |
Метод FormulaR1C1
Метод FormulaR1C1 более гибкий, поскольку он не ограничивает вас заданным диапазоном ячеек. Пример ниже даст нам тот же ответ, что и приведенный выше.
123 | Sub TestCountIf ()Диапазон («D10»). FormulaR1C1 = «= СЧЁТЕСЛИ (R [-8] C: R [-1] C,» «> 5» «)»Конец подписки |
Однако, чтобы сделать формулу еще более гибкой, мы могли бы изменить код, чтобы он выглядел так:
123 | Sub TestCountIf ()ActiveCell.FormulaR1C1 = «= СЧЁТЕСЛИ (R [-8] C: R [-1] C,» «> 5» «)»Конец подписки |
Где бы вы ни находились на своем листе, формула затем подсчитает ячейки, которые соответствуют критериям непосредственно над ней, и поместит ответ в вашу ActiveCell. На диапазон внутри функции СЧЁТЕСЛИ необходимо ссылаться с использованием синтаксиса строки (R) и столбца (C).
Оба эти метода позволяют использовать динамические формулы Excel в VBA.
Теперь вместо значения в D10 будет формула.
Текст вашей ссылки
Вы поможете развитию сайта, поделившись страницей с друзьями
Criteria-based functions are the rulers of Excel in calculations. At the beginning of learning Excel, we must have learned the COUNTIF process in Excel. In our earlier articles, we have shown you how to work with the COUNTIF function in Excel VBA.
Refer to our article on the COUNTIF Formula in ExcelThe COUNTIF function in Excel counts the number of cells within a range based on pre-defined criteria. It is used to count cells that include dates, numbers, or text. For example, COUNTIF(A1:A10,”Trump”) will count the number of cells within the range A1:A10 that contain the text “Trump”
read more to learn the basics of the COUNTIF function in Excel VBA. This article will show you how to use the same function in VBA coding. Now, we will see the same formula in VBA. First, COUNTIF is not a VBA function but a worksheet function that we can access under the worksheet function class.
Table of contents
- VBA COUNTIF
- Example of Excel VBA Countif Function
- Arrive Result with Variables
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA COUNTIF (wallstreetmojo.com)
Example of Excel VBA Countif Function
Let us see a simple example.
You can download this VBA Countif Function Excel Template here – VBA Countif Function Excel Template
Look at the below example of counting values from the lot.
The above image shows city names from cells A1 to A10. So, for example, in cell C3, we need to count how many times the city name “Bangalore” appears in the range A1 to A10.
Follow the below steps to write the code to apply the COUNTIF function.
Step 1: Start the Sub procedure.
Code:
Option ExplicitVBA option explicitly makes a user mandatory to declare all the variables before using them; any undefined variable will throw an error while coding execution. We can enable it for all codes from options to require variable declaration.read more Sub Countif_Example1() End Sub
Step 2: Since we need to store the result in cell C3, start the Range(“C3”).Value.
Code:
Sub Countif_Example1() Range("C3").Value = End Sub
Step 3: In cell C3, by applying the Excel VBA COUNTIF function, we are trying to arrive at the result. So to access the function, we need first to use the Worksheet function class.
Code:
Sub Countif_Example1() Range("C3").Value = WorksheetFunction. End Sub
Step 4: From the list, select the Excel VBA COUNTIF function.
Code:
Sub Countif_Example1() Range("C3").Value = WorksheetFunction.CountIf( End Sub
Step 5: If you look at the parameters of the VBA COUNTIF function, we do not see the parameter as we see in the worksheet.
As we can see in the above image in the worksheet, we have exact syntax, but in VBA, we can see only Arg 1 and Arg 2.
Arg 1 is Range, so select the range as A1 to A10.
Code:
Sub Countif_Example1() Range("C3").Value = WorksheetFunction.CountIf(Range("A1:A10"), End Sub
Step 6: Arg 2 is what is the value we need to count from the range A1 to A10. In this example, we need to calculate “Bangalore.”
Code:
Sub Countif_Example1() Range("C3").Value = WorksheetFunction.CountIf(Range("A1:A10"), "Bangalore") End Sub
We have completed it now.
Run the code to see the result in cell C3.
We got the result as 4. Since the city name “Bangalore” appears in cells A1, A4, A7, and A10 VBA COUNTIF function returns the product as 4.
If you can see VBA code has returned only the result of the formula, we do not get to know the procedure in the formula bar.
We need to write the code slightly differently to arrive at the formula. Below is the code for applying the formula to the cell.
Code:
Sub Countif_Example1() Range("C3").Formula = "=CountIf(A1:A10, ""Bangalore"")" End Sub
It will apply the formula to cell C3.
Arrive Result with Variables
Variables are an integral part of any coding language. Therefore, we must declare variables to work efficiently with the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. For example, look at the below code.
Code:
Sub Countif_Example2() Dim ValuesRange As Range Dim ResultCell As Range Dim CriteriaValue As String Set ValuesRange = Range("A1:A10") Set ResultCell = Range("C3") CriteriaValue = "Bangalore" ResultCell = WorksheetFunction.CountIf(ValuesRange, CriteriaValue) End Sub
Let us decode the code for you to understand better.
Firstly, we have declared the two variables as Range.
Dim ValuesRange As Range: This is to reference the list of values.
Dim ResultCell As Range: This to reference the result cell.
Then, we have set the range of references to both variables.
Set ValuesRange = Range(“A1: A10”): This is the range where all the city names are there.
Set ResultCell = Range(“C3”): In this cell, we will store the result of the COUNTIF function.
In the meantime, we have declared one more variable to store the criteria value.
Dim CriteriaValue As String
CriteriaValue = “Bangalore”
So, the variable “CriteriaValue” holds the value “Bangalore.”
As usual, we have applied the COUNTIF function in the next line.
ResultCell = WorksheetFunction.CountIf(ValuesRange, CriteriaValue)
Like this, we can apply the COUNTIF function in Excel VBA to fit our needs.
Recommended Articles
This article has been a guide to VBA COUNTIF. Here, we look at the working of the COUNTIF Function in Excel VBA along with practical examples and a downloadable Excel template. Below are some useful articles related to VBA: –
- VBA Like Operator
- Count in VBA
- Countif not Blank in Excel
- COUNTIF Examples in Excel