Счет значений в excel vba

Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами Count, CountA и CountBlank объекта WorksheetFunction из кода VBA Excel.

Метод WorksheetFunction.Count

Определение

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

Метод WorksheetFunction.Count подсчитывает в заданном диапазоне (массиве) количество ячеек (элементов массива), содержащих числа, и возвращает значение типа Double.

Синтаксис

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

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

Параметры

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

Параметр Описание
Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

Примечания

  • Метод WorksheetFunction.Count позволяет получить количество числовых значений в диапазоне ячеек или в массиве.
  • При подсчете учитываются аргументы, которые являются числами, датами или текстовым представлением чисел.
  • Логические значения учитываются при подсчете только в том случае, если они введены непосредственно в список аргументов.

Метод WorksheetFunction.CountA

Определение

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

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

Синтаксис

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

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

Параметры

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

Параметр Описание
Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

Примечания

  • Метод WorksheetFunction.CountA позволяет получить количество непустых ячеек в заданном диапазоне.
  • Непустыми являются ячейки, которые содержат любые данные, включая значения ошибок и пустые строки ("").
  • Тесты показывают, что метод WorksheetFunction.CountA в массиве, созданном путем присвоения ему значений диапазона, содержащего пустые ячейки, все равно считает все элементы массива, как содержащие значения.

Метод WorksheetFunction.CountBlank

Определение

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

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

Синтаксис

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

WorksheetFunction.CountBlank(Arg1)

Параметры

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

Параметр Описание
Arg1 Диапазон, в котором необходимо подсчитать количество пустых ячеек.

Примечания

  • Метод WorksheetFunction.CountBlank позволяет получить количество пустых ячеек в заданном диапазоне.
  • Пустыми являются ячейки, которые не содержат никаких данных.
  • Также подсчитываются, как пустые, ячейки с формулами, которые возвращают пустые строки ("").
  • Ячейки с нулевыми значениями в подсчете не участвуют.

Примеры

Таблица для строк кода VBA Excel со ссылками на диапазон "A1:C5", а также с массивом его значений в качестве аргументов:

Примеры с WorksheetFunction.Count

Sub Primer1()

Dim n As Double, a() As Variant

    n = WorksheetFunction.Count(Range(«A1:C5»))

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

    a = Range(«A1:C5»)

    n = WorksheetFunction.Count(a)

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

    n = WorksheetFunction.Count(«раз», «два», «три», 1, 2, 3)

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

    n = WorksheetFunction.Count(«раз», «два», «три», «1», «2», «3», 1, 2, 3)

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

    n = WorksheetFunction.Count(Empty, Empty, 0, 0, «», «»)

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

    n = WorksheetFunction.Count(True, False, «True», «False»)

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

End Sub

Метод WorksheetFunction.Count можно использовать для подсчета количества числовых значений в массиве, если он создан путем присвоения ему значений диапазона. Тогда логические значения ИСТИНА и ЛОЖЬ, если они встречаются в диапазоне, в подсчете количества числовых значений не участвуют.

Примеры с WorksheetFunction.CountA

Sub Primer2()

Dim n As Double, a() As Variant

    n = WorksheetFunction.CountA(Range(«A1:C5»))

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

    a = Range(«A1:C5»)

    n = WorksheetFunction.CountA(a)

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

    n = WorksheetFunction.CountA(«раз», «два», «три», 1, 2, 3)

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

    n = WorksheetFunction.CountA(Empty, Empty, 0, 0, «», «»)

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

End Sub

Примеры с WorksheetFunction.CountBlank

Sub Primer3()

Dim n As Double, a As Range

    n = WorksheetFunction.CountBlank(Range(«A1:C5»))

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

    Set a = Range(«A1:C5»)

    n = WorksheetFunction.CountBlank(a)

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

End Sub

Следующая статья по этой теме: VBA Excel. Методы CountIf и CountIfs.


In this Article

  • COUNT WorksheetFunction
  • Assigning a Count result to a Variable
  • COUNT with a Range Object
  • COUNT Multiple Range Objects
  • Using COUNTA
  • Using COUNTBLANKS
  • Using the COUNTIF Function
  • Disadvantages of WorksheetFunction
    • Using the Formula Method
    • Using the FormulaR1C1 Method

This tutorial will show you how to use the Excel COUNT function in VBA

The VBA COUNT function is used to count the number of cells in your Worksheet that have values in them. It is accessed using the WorksheetFunction method in VBA.

COUNT 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 COUNT function is one of them.

Sub TestCountFunctino
  Range("D33") = Application.WorksheetFunction.Count(Range("D1:D32"))
End Sub

vba count syntax

You are able to have up to 30 arguments in the COUNT function. Each of the arguments must refer to a range of cells.

This example below will count how many cells are populated with values are in cells D1 to D9

Sub TestCount()   
   Range("D10") = Application.WorksheetFunction.Count(Range("D1:D9"))
End Sub

The example below will count how many values are in a range in column D and in a range in column F. If you do not type the Application object, it will be assumed.

Sub TestCountMultiple()
   Range("G8") = WorksheetFunction.Count(Range("G2:G7"), Range("H2:H7"))
End Sub

Assigning a Count result to a Variable

You may want to use the result of your formula elsewhere in code rather than writing it directly back to and Excel Range.  If this is the case, you can assign the result to a variable to use later in your code.

Sub AssignCount()
   Dim result As Integer
'Assign the variable   
   result = WorksheetFunction.Count(Range("H2:H11"))
'Show the result
   MsgBox "The number of cells populated with values is " & result
End Sub

vba count values

COUNT 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 TestCountRange()
   Dim rng As Range
'assign the range of cells
   Set rng = Range("G2:G7")
'use the range in the  formula
   Range("G8") = WorksheetFunction.Count(rng)
'release the range object
  Set rng = Nothing
End Sub

COUNT Multiple Range Objects

Similarly, you can count how many cells are populated with values in multiple Range Objects.

Sub TestCountMultipleRanges() 
   Dim rngA As Range 
   Dim rngB as Range
'assign the range of cells 
   Set rngA = Range("D2:D10") 
   Set rngB = Range("E2:E10")   
'use the range in the formula 
Range("E11") = WorksheetFunction.Count(rngA, rngB)
 'release the range object
  Set rngA = Nothing 
  Set rngB = Nothing
End Sub

Using COUNTA

The count will only count the VALUES in cells, it will not count the cell if the cell has text in it. To count the cells which are populated with any sort of data, we would need to use the COUNTA function.

Sub TestCountA()
   Range("B8) = Application.WorksheetFunction.CountA(Range("B1:B6")) 
End Sub

In the example below, the COUNT function would return a zero as there are no values in column B, while it would return a 4 for column C. The COUNTA function however, would count the cells with Text in them and would return a value of 5 in column B while still returning a value of 4 in column C.

vba count diff counta

Using COUNTBLANKS

The COUNTBLANKS function will only count the Blank Cells in the Range of cells – ie cells that have no data in them at all.

Sub TestCountBlank()   
   Range("B8) = Application.WorksheetFunction.CountBlanks(Range("B1:B6")) 
End Sub

In the example below, column B has no blank cells while column C has one blank cell.

vba count diff count blanks

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!

automacro

Learn More

Using the COUNTIF Function

Another worksheet function that can be used is the COUNTIF function.

Sub TestCountIf()
   Range("H14") = WorksheetFunction.CountIf(Range("H2:H10"), ">0")
   Range("H15") = WorksheetFunction.CountIf(Range("H2:H10"), ">100")
   Range("H16") = WorksheetFunction.CountIf(Range("H2:H10"), ">1000")
   Range("H17") = WorksheetFunction.CountIf(Range("H2:H10"), ">10000")
End Sub

The procedure above will only count the cells with values in them if the criteria is matched – greater than 0, greater than 100, greater than 1000 and greater than 10000.  You have to put the criteria within quotation marks for the formula to work correctly.

vba count countif eg

Disadvantages of WorksheetFunction

When you use the WorksheetFunction to count the values in 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.

vba count static

In the example above, the procedure TestCount has counted up the cells in column H where a value is present.  As you can see in the formula bar, this result is a figure and not a formula.

If any of the values change therefore in the Range(H2:H12), the results in H14 will NOT change.

Instead of using the WorksheetFunction.Count, you can use VBA to apply a Count Function to a cell using the Formula or FormulaR1C1 methods.

Using the Formula Method

The formula method allows you to point specifically to a range of cells eg: H2:H12 as shown below.

Sub TestCountFormula
  Range("H14").Formula = "=Count(H2:H12)"
End Sub

vba formula test count formula

VBA Programming | Code Generator does work for you!

Using the FormulaR1C1 Method

The FromulaR1C1 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 TestCountFormula()
   Range("H14").Formula = "=Count(R[-9]C:R[-1]C)"
End Sub

vba count formula r1c1

However, to make the formula more flexible, we could amend the code to look like this:

Sub TestCountFormula() 
   ActiveCell.FormulaR1C1 = "=Count(R[-11]C:R[-1]C)" 
End Sub

Wherever you are in your worksheet, the formula will then count the values in the 12 cells directly above it and place the answer into your ActiveCell. The Range inside the COUNT 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 H14 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.

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

COUNTA Worksheet Function in Excel VBA

In our earlier article “Excel COUNTAThe COUNTA function is an inbuilt statistical excel function that counts the number of non-blank cells (not empty) in a cell range or the cell reference. For example, cells A1 and A3 contain values but, cell A2 is empty. The formula “=COUNTA(A1,A2,A3)” returns 2.
read more
,” we have seen how to use the COUNT function to count the numerical values from the range of values. How about calculating all the costs in the field of cells? Yes, we can estimate that as well. To count all the cell values in the range of cells, we need to use the formula “COUNTA” in Excel VBA. This article will show you how to use the COUNTA function in VBA to count all the cell values in the supplied range.

Table of contents
  • COUNTA Worksheet Function in Excel VBA
    • Examples of COUNTA Function in VBA
    • Coding with Variables
    • Recommended Articles

VBA-Counta-Function

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 COUNTA (wallstreetmojo.com)

Examples of COUNTA Function in VBA

One truth is that the COUNTA function is not a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more. So your question is if it is not a VBA function, how do we use it? Nothing worries, even though it is not a VBA function; still, we can use it under the worksheet function class in VBA coding.

You can download this VBA COUNTA Excel Template here – VBA COUNTA Excel Template

Let us write the code to apply the Excel VBA COUNTA.

Step 1: Create a subprocedure name.

Step 2: Now, decide where we will store the result of the VBA COUNTA function. In this example, I want to keep the work in cell C2. So my code will be Range(“C2”).Value.

Code:

Sub Counta_Example1()

 Range("C2").Value =

End Sub

VBA Counta Example 1

Step 3: In cell C2, we need the value of the VBA COUNTA function. So, to apply the Excel VBA COUNTA function, let’s first use the worksheet function class.

Code:

Sub Counta_Example1()

 Range("C2").Value = Work

End Sub

VBA Counta Example 1-1

Step 4: After applying the worksheet function class, select the formula COUNTA by putting a dot.

Code:

Sub Counta_Example1()

 Range("C2").Value = WorksheetFunction.Count

End Sub

VBA Counta Example 1-2

Step 5: We need to supply the range of cells for counting. In this example, we need to calculate the range of cells from A1 to A11. Then, to provide the cells using the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub Counta_Example1()

 Range("C2").Value = WorksheetFunction.CountA(Range("A1:A11"))

End Sub

VBA Counta Example 1-3

Let us run the code to get the result in cell C2.

VBA Counta Example 1-4

So, the VBA COUNTA returns the same result as well.

Like this, we can use COUNTA to count the non-empty or non-blank cells from the supplied range.

Coding with Variables

VBA variables are the key to building a project. Now, we can declare VBA variablesVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more and arrive at the result for the same data.

For example, look at the below code.

Code:

Sub Counta_Example2()

 Dim CountaRange As Range
 Dim CountaResultCell As Range

 Set CountaRange = Range("A1:A11")
 Set CountaResultCell = Range("C2")

 CountaResultCell = WorksheetFunction.CountA(CountaRange)

End Sub

Let us explain the above code now.

First, we have declared the variable “CountaRange” as a range to reference the range of values.

Dim CountaRange As Range

Next, we have set the reference as range A1 to A11.

Set CountaRange = Range("A1:A11")

The second variable is to reference the COUNTA result cell.

Dim CountaResultCell As Range

For this variable, we have set the cell as C2.

Set CountaResultCell = Range("C2")

As usual, we have applied the COUNTA function using variables instead of hardcoded ranges. Now, look at the old code and this 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.

Code 1:

Code 1

Code 2:

Code 2

In code 1, we have Range C2. In Code 2, we have the variable name “CountaResultCell.” Here the variable “CountaResultCell” set reference as a C2 cell. So this variable is a C2 cell now.

In code 1, the COUNTA function range is A1 to A11. In regulation 2, it is a variable called “CountaRange.” This variable holds a reference to the range A1 to A11.

That is the difference between old code and code with variables.

So, the COUNTA function helps us count all the non-empty cells from the supplied range irrespective of the data.

Recommended Articles

This article has been a guide to VBA COUNTA. Here, we learn how to use the COUNTA worksheet function in Excel VBA and examples and download an Excel template. Below are some useful Excel articles related to VBA: –

  • Exit Subprocedure in Excel VBA
  • Declare One Dimensional Array in VBA
  • Val Functions in VBA
  • COUNTIF Function in VBA

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft.

    With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.
    Let’s see Count() functions in Excel.

    1. COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers.

      Syntax:

      =COUNT(value1, value2…)

      value1: The very first item required to count numbers.
      value2: It can be specified upto 255 other entries which you want to count.

      Note:
      -> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.
      -> Arguments like logical values and text representation of numbers that are typed directly are counted.
      -> Any values that cannot be translated to numbers are ignored.

      Example:
      count

      Output:
      output

    2. COUNTA: This counts only those range of cells which are not empty.

      Syntax:

      =COUNTA(value1, value2…)

      value1: It is the first argument to be counted.
      value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.

      Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.

      Example:
      count

      Output:
      out

    3. COUNTIF:This will allow user to count the number of cells which meet a certain criteria.

      Syntax:

      =COUNTIF(where to look, what to look criteria)

      Example:
      countif

      Output:
      output

    4. COUNTIFS: It will map criteria to cells in multiple ranges and the number of times all criteria met are counted.

      Syntax:

      =COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…)

      criteria_range1: First range to evaluate criteria.
      criteria1: Criteria in any form that defines which all cells to be counted.
      criteria_range2, criteria2, … : Additional range with their criteria. Specified upto 127 range/criteria.

      Remarks:

      -> Wildcard characters can be used.
      -> If criteria meets an empty cell, it will be treated as 0 value.
      -> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.

      Example:
      COUNTIFS

      Output:
      output

    Like Article

    Save Article

    Excel VBA Count

    VBA Count Function

    In Excel, we use the count function to count the number of cells which contains numbers. Same can be done in VBA as well. In VBA, we can use the same function Count to get how many numbers of cells contain numbers. It only counts the cell with numbers. Values other than numbers cannot be counted.

    Syntax of Count in Excel VBA

    The syntax for the VBA Count function in excel is as follows:

    Syntax

    How to Use VBA Count in Excel?

    We will learn how to use a VBA Count Function with few examples in excel.

    You can download this VBA Count Excel Template here – VBA Count Excel Template

    Example #1 – VBA Count

    For implementing this we have a list of some data in column A. This list contains numbers and texts as shown below. Now we with the help of Count function in VBA we will see, how many cells are having numbers. For this, we have identified a cell at A8 position, where we will see the output of Count Function through VBA.

    numbers and texts

    Step 1: For this, we require a module. Go to Insert menu tab and click on Module option as shown below from the list.

    Module

    Step 2: After that, we will get the blank window of Module. Now in that write the subcategory of VBA Count. Or choose any other name as per your choice.

    Code:

    Sub VBACount()
    
    End Sub

    Subcategory

    Step 3: Select the range of the cell where we want to apply Count function. Here, our output cell is A8 as defined above. So we have selected it as our Range.

    Code:

    Sub VBACount()
    
    Range("A8").
    
    End Sub

    VBA CE 1.3

    Step 4: Now get the Value command, and it allows us to add the value in it.

    Code:

    Sub VBACount()
    
    Range("A8").Value =
    
    End Sub

    VBA CE 1.4

    Step 5: Now with the help of Count Function, select the range of the cells from which we want to get the count of a number of cells which contains Numbers only. Here, we have selected the range of cells from A1 to A6.

    Code:

    Sub VBACount()
    
    Range("A8").Value = "=Count(A1:A6)"
    
    End Sub

    VBA CE 1.5

    Ste 6: Once done then compile the code and run by clicking play button. As we can see below, the count of cells containing numbers is coming as 3. Which means the Count function in VBA has given the count of cells with numbers which are from cell A1 to A3.

    VBA CE 1.5

    Example #2 – VBA Count

    In a similar way, we have another set of data. But this data has some dates, number with text along with numbers and text as shown below. We have fixed a cells C12 where we will see the output of Count function through VBA.

    VBA CE 2.1

    Now we will apply the Count function and see if this can Count date and number-text cells or not. We can choose to write the new code again or we can refer the same code which we have seen in example-1 and just change the reference cells.

    Step 1: Go to Insert menu tab and click on Module option as shown below from the list.

    Code:

    Sub VBACount2()
    
    End Sub

    VBA CE 2.2

    Step 2: Select the range of cell where we want to see the output. Here that cell is C12.

    Code:

    Sub VBACount2()
    
    Range("C12").Value =
    
    End Sub

    VBA CE 2.2

    Step 3: Now use the count function in inverted commas in select the range of those cells which we need to count. Here that range is from cell C1 to C10.

    Code:

    Sub VBACount2()
    
    Range("C12").Value = "=Count(C1:C10)"
    
    End Sub

    VBA CE 2.3

    Step 4: Now run the above code.

    We will see the Count function has returned the count of cells as 6 as shown below. Which means, count function can count cells with Date as well. Here, the values which are highlighted as bold are those values which just got counted through Count function in VBA.

    VBA CE 2.4

    Example #3 – VBA Count

    There is another way to use Count Function in VBA. This method involves using Active Cells of the sheet. Here we will use the same data which we have seen in example-1.

    Active Cells

    Step 1: Open a new module and create the subcategory in the name of VBA Count as shown below.

    Code:

    Sub VBACount3()
    
    End Sub

    Subcategory

    Step 2: First, insert the ActiveCell function in VBA. This will help in selecting the range of cells.

    Code:

    Sub VBACount3()
    
    ActiveCell.
    
    End Sub

    ActiveCell Function

    Step 3: Now with the function Formula, select the row number and column number which we want to insert in Count function. Here our reference Row is starting from 1 and Column is also 1.

    Code:

    Sub VBACount3()
    
    ActiveCell.FormulaR1C1 =
    
    End Sub

    Function Formula

    Step 4: Now insert the Count function under inverted commas as shown below.

    Code:

    Sub VBACount3()
    
    ActiveCell.FormulaR1C1 = "=COUNT()"
    
    End Sub

    Count function

    Step 5: Select the range of the cells from the point where we are applying the Count function. As we are going up from A8 to A1 so row count will be “-7” and column is first to nothing is mentioned to the row count “-2” from the starting point which is cell A8.

    Code:

    Sub VBACount3()
    
    ActiveCell.FormulaR1C1 = "=COUNT(R[-7]C:R[-2]C)"
    
    End Sub

    applying the Count function

    Step 6: Now select the range of cell where we want to see the output. Here at this range cell A8, we will see the cursor as well.

    Code:

    Sub VBACount3()
    
    ActiveCell.FormulaR1C1 = "=COUNT(R[-7]C:R[-2]C)"
    Range("B8").Select
    
    End Sub

    Range of Cells

    Step 7: Now run the code. We will see, the count function has returned the same count of number as 3 which we got in example-1.

    Count of Number

    Pros of VBA Count

    1. It is as easy as applying Count Function in excel.
    2. This is one of the easiest function that could be automated through VBA.
    3. If the process Count is repeating multiple times then automating the same with the help of Count function in VBA is quite a time saving and effort minimizing way.

    Things to Remember

    • While applying the count function in VBA, always quote the function name in inverted commas.
    • As we use Count in Excel, the same way is also seen while applying Count Function in VBA.
    • The process of applying VBA Count can be done by recoding a macro as well.
    • Always save the written code in VBA in Macro enable excel file format to avoid losing code.

    Recommended Articles

    This is a guide to VBA Count. Here we discuss how to use Excel VBA Count Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

    1. VBA Copy Paste
    2. VBA Month
    3. VBA Subscript out of Range
    4. VBA Selecting Range

    Содержание

    • COUNT рабочий лист
    • Присвоение результата подсчета переменной
    • COUNT с объектом диапазона
    • COUNT несколько объектов диапазона
    • Использование COUNTA
    • Использование COUNTBLANKS
    • Использование функции СЧЁТЕСЛИ
    • Недостатки WorksheetFunction

    Из этого туториала Вы узнаете, как использовать функцию Excel COUNT в VBA.

    Функция VBA COUNT используется для подсчета количества ячеек на вашем листе, в которых есть значения. Доступ к нему осуществляется с помощью метода WorksheetFunction в VBA.

    COUNT рабочий лист

    Объект WorksheetFunction можно использовать для вызова большинства функций Excel, доступных в диалоговом окне «Вставить функцию» в Excel. Функция СЧЁТ — одна из них.

    123 Sub TestCountFunctinoДиапазон («D33») = Application.WorksheetFunction.Count (Диапазон («D1: D32»))Конец подписки

    У вас может быть до 30 аргументов в функции COUNT. Каждый из аргументов должен относиться к диапазону ячеек.

    В этом примере ниже будет подсчитано, сколько ячеек заполнено значениями в ячейках с D1 по D9.

    123 Sub TestCount ()Диапазон («D10») = Application.WorksheetFunction.Count (Диапазон («D1: D9»))Конец подписки

    В приведенном ниже примере будет подсчитано, сколько значений находится в диапазоне в столбце D и в диапазоне в столбце F. Если вы не введете объект Application, он будет принят.

    123 Sub TestCountMultiple ()Диапазон («G8») = WorksheetFunction.Count (Диапазон («G2: G7»), Диапазон («H2: H7»))Конец подписки

    Присвоение результата подсчета переменной

    Возможно, вы захотите использовать результат своей формулы в другом месте кода, а не записывать его непосредственно обратно в Excel Range. В этом случае вы можете присвоить результат переменной, которая будет использоваться позже в вашем коде.

    1234567 Sub AssignCount ()Уменьшить результат как целое число’Назначьте переменнуюрезультат = WorksheetFunction.Count (Range («H2: H11»))’Показать результатMsgBox «Число ячеек, заполненных значениями» & resultКонец подписки

    COUNT с объектом диапазона

    Вы можете назначить группу ячеек объекту Range, а затем использовать этот объект Range с Рабочий лист объект.

    123456789 Sub TestCountRange ()Dim rng As Range’назначить диапазон ячеекУстановить rng = Диапазон («G2: G7»)’используйте диапазон в формулеДиапазон («G8») = WorksheetFunction.Count (rng)’отпустить объект диапазонаУстановить rng = ничегоКонец подписки

    COUNT несколько объектов диапазона

    Точно так же вы можете подсчитать, сколько ячеек заполнено значениями в нескольких объектах диапазона.

    123456789101112 Sub TestCountMultipleRanges ()Dim rngA As ДиапазонDim rngB as Range’назначить диапазон ячеекУстановите rngA = Range («D2: D10»)Установите rngB = Range («E2: E10»)’используйте диапазон в формулеДиапазон («E11») = WorksheetFunction.Count (rngA, rngB)’отпустить объект диапазонаУстановите rngA = NothingУстановить rngB = НичегоКонец подписки

    Использование COUNTA

    При подсчете будут учитываться только ЗНАЧЕНИЯ в ячейках, он не будет учитывать ячейку, если в ячейке есть текст. Для подсчета ячеек, заполненных любыми данными, нам понадобится функция COUNTA.

    123 Sub TestCountA ()Диапазон («B8) = Application.WorksheetFunction.CountA (Диапазон (» B1: B6 «))Конец подписки

    В приведенном ниже примере функция COUNT вернет ноль, поскольку в столбце B нет значений, тогда как функция COUNTA вернет 4 для столбца C. Однако функция COUNTA подсчитает ячейки с текстом в них и вернет значение 5 в столбце B, но по-прежнему возвращает значение 4 в столбце C.

    Использование COUNTBLANKS

    Функция COUNTBLANKS будет подсчитывать только пустые ячейки в диапазоне ячеек, то есть ячейки, в которых вообще нет данных.

    123 Sub TestCountBlank ()Диапазон («B8) = Application.WorksheetFunction.CountBlanks (Диапазон (» B1: B6 «))Конец подписки

    В приведенном ниже примере в столбце B нет пустых ячеек, а в столбце C — одна пустая ячейка.

    Использование функции СЧЁТЕСЛИ

    Еще одна функция рабочего листа, которую можно использовать, — это функция СЧЁТЕСЛИ.

    123456 Sub TestCountIf ()Range («H14») = WorksheetFunction.CountIf (Range («H2: H10»), «> 0»)Range («H15») = WorksheetFunction.CountIf (Range («H2: H10»), «> 100»)Range («H16») = WorksheetFunction.CountIf (Range («H2: H10»), «> 1000»)Range («H17») = WorksheetFunction.CountIf (Range («H2: H10»), «> 10000»)Конец подписки

    Приведенная выше процедура будет подсчитывать ячейки со значениями в них, только если критерии совпадают — больше 0, больше 100, больше 1000 и больше 10000. Вы должны заключить критерии в кавычки, чтобы формула работала правильно.

    Недостатки WorksheetFunction

    Когда вы используете Рабочий лист для подсчета значений в диапазоне на вашем листе возвращается статическое значение, а не гибкая формула. Это означает, что при изменении ваших цифр в Excel значение, возвращаемое Рабочий лист не изменится.

    В приведенном выше примере процедура TestCount подсчитала ячейки в столбце H, где присутствует значение. Как вы можете видеть в строке формул, это число, а не формула.

    Если любое из значений изменится в диапазоне (H2: H12), результаты в H14 будут НЕТ изменение.

    Вместо использования WorksheetFunction.Count, вы можете использовать VBA для применения функции подсчета к ячейке с помощью Формула или Формула R1C1 методы.

    Использование метода формул

    Метод формулы позволяет указать конкретный диапазон ячеек, например: H2: H12, как показано ниже.

    123 Sub TestCountFormulaДиапазон («H14»). Формула = «= Count (H2: H12)»Конец подписки

    Использование метода FormulaR1C1

    Метод FromulaR1C1 более гибкий, поскольку он не ограничивает вас заданным диапазоном ячеек. Пример ниже даст нам тот же ответ, что и приведенный выше.

    123 Sub TestCountFormula ()Диапазон («H14»). Формула = «= Счетчик (R [-9] C: R [-1] C)»Конец подписки

    Однако, чтобы сделать формулу более гибкой, мы могли бы изменить код, чтобы он выглядел так:

    123 Sub TestCountFormula ()ActiveCell.FormulaR1C1 = «= Счетчик (R [-11] C: R [-1] C)»Конец подписки

    Где бы вы ни находились на своем листе, формула затем подсчитает значения в 12 ячейках непосредственно над ней и поместит ответ в вашу ActiveCell. На диапазон внутри функции COUNT следует ссылаться с использованием синтаксиса Row (R) и Column (C).

    Оба эти метода позволяют использовать динамические формулы Excel в VBA.

    Теперь вместо значения в H14 будет формула.

    Содержание

    1. VBA Excel. Методы CountIf и CountIfs
    2. Metod WorksheetFunction.CountIf
    3. Определение
    4. Синтаксис
    5. Параметры
    6. Примечания
    7. Metod WorksheetFunction.CountIfs
    8. Определение
    9. Синтаксис
    10. Функции VBA СЧЁТЕСЛИ и СЧЁТЕСЛИ
    11. СЧЕТЕСЛИ Рабочий лист
    12. Присвоение переменной результата COUNTIF
    13. Использование СЧЁТЕСЛИМН
    14. Использование COUNTIF с объектом диапазона
    15. Использование COUNTIFS для объектов с несколькими диапазонами
    16. СЧЁТЕСЛИ Формула
    17. Формула Метод
    18. Метод FormulaR1C1
    19. VBA Excel. Методы Count, CountA и CountBlank
    20. Метод WorksheetFunction.Count
    21. Определение
    22. Синтаксис
    23. Параметры
    24. Примечания
    25. Метод WorksheetFunction.CountA
    26. Определение
    27. Синтаксис
    28. Параметры
    29. Примечания
    30. Метод WorksheetFunction.CountBlank
    31. Определение
    32. Синтаксис
    33. Параметры
    34. Примечания
    35. Примеры
    36. VBA COUNT
    37. COUNT WorksheetFunction
    38. Assigning a Count result to a Variable
    39. COUNT with a Range Object
    40. COUNT Multiple Range Objects
    41. Using COUNTA
    42. Using COUNTBLANKS
    43. VBA Coding Made Easy
    44. Using the COUNTIF Function
    45. Disadvantages of WorksheetFunction
    46. Using the Formula Method
    47. Using the FormulaR1C1 Method
    48. VBA Code Examples Add-in

    VBA Excel. Методы CountIf и CountIfs

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

    Metod WorksheetFunction.CountIf

    Определение

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

    Синтаксис

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

    Параметры

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

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

    Примечания

    • Метод WorksheetFunction.CountIf позволяет получить количество ячеек, соответствующих заданному критерию, в указанном диапазоне.
    • Примеры критериев (условий): 25 , «25» , «>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:

    Синтаксис

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

    Источник

    Функции VBA СЧЁТЕСЛИ и СЧЁТЕСЛИ

    Из этого туториала Вы узнаете, как использовать функции 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 будет формула.

    Источник

    VBA Excel. Методы Count, CountA и CountBlank

    Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами Count, CountA и CountBlank объекта WorksheetFunction из кода VBA Excel.

    Метод WorksheetFunction.Count

    Определение

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

    Синтаксис

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

    Параметры

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

    Параметр Описание
    Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

    Примечания

    • Метод WorksheetFunction.Count позволяет получить количество числовых значений в диапазоне ячеек или в массиве.
    • При подсчете учитываются аргументы, которые являются числами, датами или текстовым представлением чисел.
    • Логические значения учитываются при подсчете только в том случае, если они введены непосредственно в список аргументов.

    Метод WorksheetFunction.CountA

    Определение

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

    Синтаксис

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

    Параметры

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

    Параметр Описание
    Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

    Примечания

    • Метод WorksheetFunction.CountA позволяет получить количество непустых ячеек в заданном диапазоне.
    • Непустыми являются ячейки, которые содержат любые данные, включая значения ошибок и пустые строки ( «» ).
    • Тесты показывают, что метод WorksheetFunction.CountA в массиве, созданном путем присвоения ему значений диапазона, содержащего пустые ячейки, все равно считает все элементы массива, как содержащие значения.

    Метод WorksheetFunction.CountBlank

    Определение

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

    Синтаксис

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

    Параметры

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

    Параметр Описание
    Arg1 Диапазон, в котором необходимо подсчитать количество пустых ячеек.

    Примечания

    • Метод WorksheetFunction.CountBlank позволяет получить количество пустых ячеек в заданном диапазоне.
    • Пустыми являются ячейки, которые не содержат никаких данных.
    • Также подсчитываются, как пустые, ячейки с формулами, которые возвращают пустые строки ( «» ).
    • Ячейки с нулевыми значениями в подсчете не участвуют.

    Примеры

    Таблица для строк кода VBA Excel со ссылками на диапазон «A1:C5» , а также с массивом его значений в качестве аргументов:

    Источник

    VBA COUNT

    In this Article

    This tutorial will show you how to use the Excel COUNT function in VBA

    The VBA COUNT function is used to count the number of cells in your Worksheet that have values in them. It is accessed using the WorksheetFunction method in VBA.

    COUNT 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 COUNT function is one of them.

    You are able to have up to 30 arguments in the COUNT function. Each of the arguments must refer to a range of cells.

    This example below will count how many cells are populated with values are in cells D1 to D9

    The example below will count how many values are in a range in column D and in a range in column F. If you do not type the Application object, it will be assumed.

    Assigning a Count result to a Variable

    You may want to use the result of your formula elsewhere in code rather than writing it directly back to and Excel Range. If this is the case, you can assign the result to a variable to use later in your code.

    COUNT 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.

    COUNT Multiple Range Objects

    Similarly, you can count how many cells are populated with values in multiple Range Objects.

    Using COUNTA

    The count will only count the VALUES in cells, it will not count the cell if the cell has text in it. To count the cells which are populated with any sort of data, we would need to use the COUNTA function.

    In the example below, the COUNT function would return a zero as there are no values in column B, while it would return a 4 for column C. The COUNTA function however, would count the cells with Text in them and would return a value of 5 in column B while still returning a value of 4 in column C.

    Using COUNTBLANKS

    The COUNTBLANKS function will only count the Blank Cells in the Range of cells – ie cells that have no data in them at all.

    In the example below, column B has no blank cells while column C has one blank cell.

    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!

    Using the COUNTIF Function

    Another worksheet function that can be used is the COUNTIF function.

    The procedure above will only count the cells with values in them if the criteria is matched – greater than 0, greater than 100, greater than 1000 and greater than 10000. You have to put the criteria within quotation marks for the formula to work correctly.

    Disadvantages of WorksheetFunction

    When you use the WorksheetFunction to count the values in 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 TestCount has counted up the cells in column H where a value is present. As you can see in the formula bar, this result is a figure and not a formula.

    If any of the values change therefore in the Range(H2:H12), the results in H14 will NOT change.

    Instead of using the WorksheetFunction.Count, you can use VBA to apply a Count Function to a cell using the Formula or FormulaR1C1 methods.

    Using the Formula Method

    The formula method allows you to point specifically to a range of cells eg: H2:H12 as shown below.

    Using the FormulaR1C1 Method

    The FromulaR1C1 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.

    However, to make the formula more flexible, we could amend the code to look like this:

    Wherever you are in your worksheet, the formula will then count the values in the 12 cells directly above it and place the answer into your ActiveCell. The Range inside the COUNT 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 H14 instead of a value.

    VBA Code Examples Add-in

    Easily access all of the code examples found on our site.

    Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

    Источник

    Понравилась статья? Поделить с друзьями:
  • Счет заполненных ячеек в excel по условию
  • Счет фактура на оплату образец в word скачать бесплатно
  • Счет заполненных строк в excel
  • Счет фактура на оплату бланк скачать бесплатно excel
  • Счет залитых ячеек в excel