Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами 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
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.
ALFA Пользователь Сообщений: 243 |
Подскажите, как, открыв макросом стороннюю книгу, можно на определенном ее листе посчитать кол-во заполненных ячеек в столбце A. |
hk1209 Пользователь Сообщений: 271 |
|
ALFA Пользователь Сообщений: 243 |
Set wb2 = Workbooks.Open(«C:UsersU_M06TTDesktopExcelКачествоМарт 2014.xls», 0, 1) ‘открыл книгу Скажите что еще написать, я в этом не оч силен. |
ALFA Пользователь Сообщений: 243 |
#4 15.05.2014 20:31:10 Нашел решение, всем спасибо!
|
||
Scripter Пользователь Сообщений: 255 |
#5 16.05.2014 01:48:48 так кол-во заполненных
так номер последней строки
Изменено: Scripter — 16.05.2014 08:58:46 |
||||
ALFA Пользователь Сообщений: 243 |
А если необходимо открыв книгу, посчитать Кол-во заполненных ячеек, предварительно выбрав лист, как использовать Worksheetfunction.CountA(Columns(1)) |
Scripter Пользователь Сообщений: 255 |
#7 16.05.2014 17:44:27 Если нужно чтоб при открытии книги срабатывал код, то нужно поместить код в «Эта книга»
Если вам нужно посчитать ВСЕ заполненные (не найти последнюю строку) ячейки на листе:
В определенном столбце
или
Найти последнюю строку на листе, если последнее значение которое увеличивает диапазон может быть в любом столбце
Найти последнюю строку на листе по определенному полю
Изменено: Scripter — 16.05.2014 17:48:46 |
|||||
My first column is an index, with monotonously increasing numbers, which ends at a non predictable point.
Now I want to find out, how many entries this column has. Is there a better way than iterating throug this and watch out for an empty cell?
eli-k
10.7k11 gold badges43 silver badges44 bronze badges
asked Jul 14, 2010 at 9:27
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore «breaks» in your data and find the true last row.
answered Oct 6, 2011 at 21:48
MrKowzMrKowz
2713 silver badges3 bronze badges
1
One way is to: (Assumes index column begins at A1)
MsgBox Range("A1").End(xlDown).Row
Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.
You can select the next empty cell with:
Range("A1").End(xlDown).Offset(1, 0).Select
If you need the end of a dataset (including blanks), try: Range(«A:A»).SpecialCells(xlLastCell).Row
answered Jul 14, 2010 at 10:03
Alex K.Alex K.
170k30 gold badges263 silver badges286 bronze badges
2
You can also use
Cells.CurrentRegion
to give you a range representing the bounds of your data on the current active sheet
Msdn says on the topic
Returns a Range object that represents
the current region. The current region
is a range bounded by any combination
of blank rows and blank columns.
Read-only.
Then you can determine the column count via
Cells.CurrentRegion.Columns.Count
and the row count via
Cells.CurrentRegion.Rows.Count
answered Jul 14, 2010 at 10:18
almog.orialmog.ori
7,8291 gold badge35 silver badges49 bronze badges
1
You may also use:
UsedRange.Rows.Count
answered Jul 2, 2011 at 5:38
AMIBAMIB
3,1823 gold badges19 silver badges19 bronze badges
0
To find the last filled column use the following :
lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Hugo Dozois
8,05712 gold badges53 silver badges58 bronze badges
answered Mar 6, 2013 at 18:13
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:
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.
Step 1: For this, we require a module. Go to Insert menu tab and click on Module option as shown below from the list.
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
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
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
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
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.
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.
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
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
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
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.
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.
Step 1: Open a new module and create the subcategory in the name of VBA Count as shown below.
Code:
Sub VBACount3() End Sub
Step 2: First, insert the ActiveCell function in VBA. This will help in selecting the range of cells.
Code:
Sub VBACount3() ActiveCell. End Sub
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
Step 4: Now insert the Count function under inverted commas as shown below.
Code:
Sub VBACount3() ActiveCell.FormulaR1C1 = "=COUNT()" End Sub
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
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
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.
Pros of VBA Count
- It is as easy as applying Count Function in excel.
- This is one of the easiest function that could be automated through VBA.
- 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 –
- VBA Copy Paste
- VBA Month
- VBA Subscript out of Range
- VBA Selecting Range
- Функция подсчета VBA
Функция подсчета VBA
В Excel мы используем функцию count для подсчета количества ячеек, которые содержат числа. То же самое можно сделать и в VBA. В VBA мы можем использовать ту же функцию Count, чтобы узнать, сколько номеров ячеек содержат числа. Считает только ячейку с числами. Значения, отличные от чисел, не могут быть подсчитаны.
Синтаксис Count в Excel VBA
Синтаксис для функции VBA Count в Excel выглядит следующим образом:
Как использовать VBA Count в Excel?
Мы узнаем, как использовать функцию подсчета VBA, с несколькими примерами в Excel.
Вы можете скачать этот шаблон VBA Count Excel здесь — Шаблон VBA Count Excel
Пример № 1 — количество VBA
Для реализации этого у нас есть список некоторых данных в столбце А. Этот список содержит цифры и тексты, как показано ниже. Теперь мы с помощью функции Count в VBA увидим, сколько ячеек имеют числа. Для этого мы определили ячейку в позиции A8, где мы увидим вывод функции Count через VBA.
Шаг 1: Для этого нам нужен модуль. Перейдите на вкладку меню «Вставка» и выберите «Модуль», как показано ниже из списка.
Шаг 2: После этого мы получим пустое окно модуля. Теперь в это напишите подкатегорию VBA Count. Или выберите любое другое имя согласно вашему выбору.
Код:
Sub VBACount () End Sub
Шаг 3: Выберите диапазон ячейки, в которой мы хотим применить функцию Count. Здесь нашей выходной ячейкой является A8, как определено выше. Таким образом, мы выбрали его в качестве нашего диапазона .
Код:
Sub VBACount () Range ("A8"). End Sub
Шаг 4: Теперь получите команду Value, и это позволит нам добавить значение в нее.
Код:
Sub VBACount () Range ("A8"). Значение = End Sub
Шаг 5: Теперь с помощью функции подсчета выберите диапазон ячеек, из которого мы хотим получить количество ячеек, которое содержит только числа. Здесь мы выбрали диапазон ячеек от А1 до А6.
Код:
Sub VBACount () Range ("A8"). Value = "= Count (A1: A6)" End Sub
Ste 6: После этого скомпилируйте код и запустите, нажав кнопку воспроизведения. Как мы видим ниже, количество ячеек, содержащих числа, равно 3. Что означает, что функция Count в VBA дала счетчик ячеек с номерами от A1 до A3.
Пример № 2 — Количество VBA
Аналогичным образом, у нас есть другой набор данных. Но эти данные имеют некоторые даты, число с текстом вместе с цифрами и текст, как показано ниже. Мы исправили ячейку C12, где мы увидим вывод функции Count через VBA.
Теперь мы применим функцию Count и посмотрим, может ли она считать даты и числовые текстовые ячейки или нет. Мы можем снова написать новый код или ссылаться на тот же код, который мы видели в примере 1, и просто изменить ячейки ссылки.
Шаг 1: Перейдите на вкладку меню «Вставка» и выберите пункт «Модуль», как показано ниже в списке.
Код:
Sub VBACount2 () End Sub
Шаг 2: Выберите диапазон ячеек, в котором мы хотим увидеть вывод. Вот эта ячейка C12.
Код:
Sub VBACount2 () Range ("C12"). Значение = End Sub
Шаг 3: Теперь используйте функцию подсчета в кавычках для выбора диапазона тех ячеек, которые нам нужно посчитать. Здесь этот диапазон от ячейки C1 до C10.
Код:
Sub VBACount2 () Range ("C12"). Value = "= Count (C1: C10)" End Sub
Шаг 4: Теперь запустите приведенный выше код.
Мы увидим, что функция Count вернула счетчик 6, как показано ниже. Это означает, что функция count может также считать ячейки с датой. Здесь значения, выделенные жирным шрифтом, являются значениями, которые только что были подсчитаны с помощью функции Count в VBA.
Пример № 3 — Количество VBA
Есть еще один способ использовать функцию подсчета в VBA. Этот метод предполагает использование активных ячеек листа. Здесь мы будем использовать те же данные, которые мы видели в примере-1.
Шаг 1: Откройте новый модуль и создайте подкатегорию с именем VBA Count, как показано ниже.
Код:
Sub VBACount3 () End Sub
Шаг 2. Сначала вставьте функцию ActiveCell в VBA. Это поможет в выборе диапазона ячеек.
Код:
Sub VBACount3 () ActiveCell. End Sub
Шаг 3: Теперь с помощью функции Formula выберите номер строки и номер столбца, которые мы хотим вставить в функцию Count. Здесь наша ссылочная строка начинается с 1, а столбец также равен 1.
Код:
Sub VBACount3 () ActiveCell.FormulaR1C1 = End Sub
Шаг 4: Теперь вставьте функцию Count под кавычками, как показано ниже.
Код:
Sub VBACount3 () ActiveCell.FormulaR1C1 = "= COUNT ()" End Sub
Шаг 5: Выберите диапазон ячеек от точки, где мы применяем функцию Count. По мере того, как мы поднимаемся от A8 к A1, количество строк будет равно « -7 », а столбец будет первым, но ничто не будет упомянуто в числе строк «-2» от начальной точки, которая является ячейкой A8 .
Код:
Sub VBACount3 () ActiveCell.FormulaR1C1 = "= COUNT (R (-7) C: R (-2) C)" End Sub
Шаг 6: Теперь выберите диапазон ячеек, в котором мы хотим увидеть результат. Здесь, в этой ячейке диапазона A8, мы также увидим курсор.
Код:
Sub VBACount3 () ActiveCell.FormulaR1C1 = "= COUNT (R (-7) C: R (-2) C)" Range ("B8"). Выберите End Sub
Шаг 7: Теперь запустите код. Мы увидим, что функция count вернула то же число, что и 3, которое мы получили в примере-1.
Плюсы VBA Count
- Это так же просто, как применять функцию подсчета в Excel.
- Это одна из самых простых функций, которые можно автоматизировать с помощью VBA.
- Если процесс Count повторяется несколько раз, то его автоматизация с помощью функции Count в VBA — это экономия времени и усилий.
То, что нужно запомнить
- При применении функции подсчета в VBA всегда указывайте имя функции в кавычках.
- Поскольку мы используем Count в Excel, то же самое можно увидеть и при применении Count Function в VBA.
- Процесс применения VBA Count также может быть выполнен путем перекодирования макроса.
- Всегда сохраняйте написанный код в VBA в Macro, включите формат файла Excel, чтобы избежать потери кода.
Рекомендуемые статьи
Это руководство к графу VBA. Здесь мы обсудим, как использовать функцию подсчета Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- Функция копирования и вставки в VBA
- Функция подстроки Excel
- Индекс VBA вне диапазона
- Excel ISNUMBER Formula
Подсчёт ячеек в выделенном диапазоне с учетом пустых (незаполненных).
Предположим ситуацию, что у вас есть план объекта, выполненный на координатной сетке, расчерченной в программе Excel.
Известен масштаб: Сторона клетки равна 10 см.
Необходимо посчитать площадь объекта или его отдельной части (комнаты).
Если объект прямоугольной формы всё довольно просто достаточно посчитать ячейки, вдоль вертикально нарисованной и горизонтально нарисованной стен и перемножить значения. Полученное произведение перевести из квадратных дециметров в метры квадратные.
Сложности возникают, если объект не прямоугольной формы. Для такого объекта необходимо считать площадь каждого отдельного прямоугольного участка, потом складывать полученные результаты. Процедура довольно долгая и скучная.
Для упрощения работы по подсчету ячеек в выделенном диапазоне, можно написать следующий макрос, который будет считать количество ячеек (клеток) во всём выделение и выводить значения в виде появляющегося окна (MsgBox).
Макрос подсчета количества ячеек в выделенном диапазоне выглядит следующим образом:
Sub Счет_ячеек() ‘название макроса
Dim b as integer ‘ вводим переменную b
b=0 ‘присваиваем переменной значение «0»
for each cell in selection ‘записываем цикл подсчета
b=b+1
next
MsgBox «количество ячеек » & b ‘ выводим сообщение с количеством ячеек
End sub ‘конец макроса
Присваиваем созданный макрос кнопке или сочетанию клавиш для удобства использования.
После того, как макрос посчитать количество ячеек переведите значения площади в дециметрах в метры квадратные.