EXPLANATION
This tutorial shows and explains how to count cells that do not contain a specific value using by using Excel formulas or VBA.
This tutorial provides two Excel methods that can be applied to count cells that do not contain a specific value in a selected range by using an Excel COUNTIF function combined with the not equal to sign (<>). The first method sources the value that from a cell, whilst the second method has the value (Exceldome) directly entered into the formula.
This tutorial provides two VBA methods that can be applied to count cells that do not contain a specific value in a selected range. The first method sources the value that from a cell, whilst the second method has the value (Exceldome) directly entered into the VBA code.
By including asterisk (*) in front and behind the value that we are searching for it will ensure that if there is other content in a cell, including the specific value, the formula will not count this cell.
FORMULA (value manually entered)
=COUNTIF(range,»<>»&»*value*»)
FORMULA (value sourced from cell reference)
=COUNTIF(range,»<>»&»*»&value&»*»)
ARGUMENTS
range: The range of cells you want to count from.
value: The value that is used to determine which of the cells should not be counted, from a specified range, if the cells contain this value.
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
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
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.
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 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
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.
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.
Sub TestCountFormula
Range("H14").Formula = "=Count(H2:H12)"
End Sub
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
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.
Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами 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.
-
#2
Michael — try this:
n = Worksheets(«Sheet1»).Range(«A:A»).Cells.SpecialCells(xlCellTypeConstants).Count
Legacy 12630
Guest
-
#3
Or if the column consists of constants, formulas and blanks :-
Sub Count_NonBlank_Cells()
Dim col As Integer, rng As Range, n#, b#
col = Selection.Column
If Application.WorksheetFunction.CountA(Columns(col)) = 0 Then
MsgBox «You have selected a blank column»
n = 0
Else
Set rng = Intersect(Columns(col), ActiveSheet.UsedRange)
On Error Resume Next
b = rng.Cells.SpecialCells(xlCellTypeBlanks).Count
n = rng.Cells.Count — b
On Error GoTo 0
MsgBox «The number of non-blank cells in column » & col & » is » & n
End If
End Sub
-
#4
On searching for an answer to my problem, this is exactley what i needed.
is there a way to exclude the first row (header) from this count?
Also can i then minus where coulmn c = Y
i.e if i had 400 entries(399 minus header) in column A and column be had 50 Y how could i return my count as 349? (am i asking too much)
this would be great.
-
#5
Michael — try this:
n = Worksheets(«Sheet1»).Range(«A:A»).Cells.SpecialCells(xlCellTypeConstants).Count
Excellent… It really helped me.. thnks DonkeyOte
you rock
-
#6
Hi guys,
I came across this thread after googling something similar to the title.
here is my code:
OSC = Range(«A2:A6»).Cells.SpecialCells(xlCellTypeConstants).Count
On Error Resume Next
ODC = Range(«C2:C6»).Cells.SpecialCells(xlCellTypeConstants).Count
On Error Resume Next
ULC = Range(«E2:E6»).Cells.SpecialCells(xlCellTypeConstants).Count
On Error Resume Next
If OSC > 1 Then
Selection.Sort Key1:=Range(«B2:B6»), Order1:=xlDescending, Header:=xlGuess
End If
If ODC > 1 Then
Selection.Sort Key1:=Range(«D2:D6»), Order1:=xlDescending, Header:=xlGuess
End If
If ULC > 1 Then
Selection.Sort Key1:=Range(«F2:F6»), Order1:=xlDescending, Header:=xlGuess
End If
any idea why it is doing the following:
A B C D E F
1 OS mins OD mins UL mins
2 shift change 11.88 Inspection 99.17
3 Wait for trucks 18.00 AF alarm 62.12 restart 37
4 Hosing chutes 14.67
5 Breaking over 14.50
The code seems to be putting the ones listed in column D into descending order but not column B and with column F it’s skipping F2 and putting it straight in to F3.
what i’m trying to do:
I’m trying to sort the downtimes in to descending order. The maximum that each column will have is 5 downtimes (ie. A2 to A6 etc). Some columns will have 0 and some will have 1. When a column has zero the .count function gives me an error.
Any help is greatly appreciated.
-
#7
well, the formatting stuffed up the table I put in.
Pretty much it’s doing the descending order for some columns but not others and i’m not sure why
-
#8
I was looking for this info and wanted to share the info that worked for me to achieve above task of counting non blank cells in any column.
m_Count = 20000
m_Count_column = 4
s_name=»tab name»
With Sheets(s_name)
.Cells(m_Count, 1) = «Number of Non blanks cells:»
.Cells(m_Count, m_Count_column).NumberFormat = «General»
.Cells(m_Count, m_Count_column).FormulaR1C1 = «=COUNTA(‘» & s_name & «‘!C2)-1»
Count = .Cells(m_Count, m_Count_column)
End With
Above code will store the count in Cells(m_Count, m_Count_column) of s_name temporarily and later its stored in a variable Count. Count can be used later on.
«=COUNTA(‘» & s_name & «‘!C2)-1» is the formula used to count the non blanks cells in the column 2 of tab s_name of worksheetsheet xyz. C2 means Column 2.
Regards,
Adithya
Last edited: Mar 14, 2013
-
#9
Code I am using for deleting empty columns (except for a header)
Can be adapted for purpose…
Code:
Dim lRealLastRow, lRealLastCol As Long
lRealLastRow = Cells.Find("*", Range("A1"), xlValues, , xlByRows, xlPrevious).Row
lRealLastCol = Cells.Find("*", Range("A1"), xlValues, , xlByColumns, xlPrevious).Column
For i = 1 To lRealLastCol
If lRealLastRow - WorksheetFunction.CountBlank(Intersect(Columns(i), ActiveSheet.UsedRange)) <= 1 Then _
Columns(i).EntireColumn.Delete
Next i
-
#10
This should do the job….it’s a mash-up of the comments above.
Sub countDataByColumns()
Dim lRealLastRow, lRealLastCol As Long
lRealLastRow = Cells.Find(«*», Range(«A1»), xlValues, , xlByRows, xlPrevious).Row
lRealLastCol = Cells.Find(«*», Range(«A1»), xlValues, , xlByColumns, xlPrevious).Column
For i = 1 To lRealLastCol
Set Rng = Intersect(Columns(i), ActiveSheet.UsedRange)
On Error Resume Next
b = Rng.Cells.SpecialCells(xlCellTypeBlanks).Count
n = Rng.Cells.Count — b
On Error GoTo 0
MsgBox «The number of non-blank cells in column » & Columns(i).Column & » is » & n
Next i
End Sub
Count Function in VBA Excel
VBA COUNT function, one can use to count how many cells have values in it. We must remember that it counts the cells with numbers or text enclosed in double quotes or whose values are typed directly. Those cells with random data that Excel cannot translate do not count.
In VBA, COUNT is a worksheet function that one can apply through the worksheet function class. It is not a built-in function. VBA COUNT function can count all the numerical values from the supplied range.
This article will show you how to use the COUNT function in VBA.
Table of contents
- Count Function in VBA Excel
- Examples of VBA Count Function
- VBA Count Example #1
- VBA Count Example #2
- Recommended Articles
- Examples of VBA Count Function
Examples of VBA Count Function
Let us take some practical examples of the VBA COUNT function to understand its working.
You can download this VBA Count Function Template here – VBA Count Function Template
VBA Count Example #1
Write the code on your own to apply this COUNT function in Excel VBA.
Step 1: Start the macro by starting the Sub procedure.
Code:
Sub Count_Example1() End Sub
Step 2: Now, we will store the result of the COUNT function in cell C2. So our code should be as “Range(“C2”).Value =
Code:
Sub Count_Example1() Range("C2").Value = End Sub
Step 3: Since it is not a VBA built-in 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, we must apply it through the worksheet function class. So, access through worksheet function class.
Code:
Sub Count_Example1() Range("C2").Value = Worksheetfunction.Count( End Sub
Step 4: Now supply the range as A1 to A7.
Code:
Sub Count_Example1() Range("C2").Value = WorksheetFunction.Count(Range("A1:A7")) End Sub
These are three simple steps to arrive at the result.
Now, run the code to see the result in cell C2.
As usual, we got the result as 3, like when we applied the VBA COUNT function in a worksheet.
If we observe the formula bar, we have not got the formula. Rather, we just got the result of the formula. Therefore, we must alter our code to apply the formula to cell C2. Below is the code to apply the formula.
Code:
Sub Count_Example1() Range("C2").Value = "=Count(A1:A7)" End Sub
Run 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 using the F5 key or manually. Then, this will apply the formula to cell C2.
VBA Count Example #2
Look at one more example with the COUNT function. For this example, look at the below data.
We have a few numerical and non-numerical values from A1 to A11. Therefore, we will apply the code below to count the numerical values from the range A1 to A11.
Code:
Sub Count_Example2() Range("C2").Value = "=Count(A1:A11)" End Sub
When we execute the above code manually or using the F5 key, we get the result as 5.
However, when we closely look at the data from A1 to A11, we have numerical values in cells A1, A2, A3, A4, A5, A7, and A11. So, we have numerical values in 7 cells, but the formula has returned the result as only 5.
The reason for this is when we closely look at each cell in cells A5 and A7, the values are stored as text, not as numbers. So the COUNT function has returned the result as only 5 because it treats those cells formatted or stored as text as non-numerical values and ignores the numerical count.
Like this, we can use the COUNT function in Excel as part of both worksheets and VBA functions to count the numerical values from the list.
Recommended Articles
This article has been a guide to VBA COUNT. Here, we learn how to use the VBA COUNT function to count numeric values in Excel, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –
- VBA Remove Duplicate Values
- What is VBA Split Function in Excel?
- End in VBA
- VBA ArrayList