Cell count in excel vba

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.

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

Trying to count the number of cells within a range to display on the status bar. Not sure how to count the number of cells within the range to use as the denominator for the progress bar. Any thoughts?

For Each cell In Range("E11:G28,E33:G50,E57:G74,E79:G96,E101:G118,E130:G147,E152:G169,E175:G192,E198:G215,E221:G238")
    **lTotal = Range.Cells.Count**
    Application.StatusBar = "Processing cell " & cell.AddressLocal & _
                                    "    " & Format((lCounter / lTotal), "0%")
    cell.EntireRow.Hidden = (cell.Value = "")
    lCounter = lCounter = 1
Next cell

Many thanks

Community's user avatar

asked Jun 9, 2014 at 9:48

user3450844's user avatar

3

This version looks at your range, row by row, rather than by cell by cell

It also turns off ScreenUpdating to avoid flicker, resets the StatusBar etc

Sub ReCut() 
Dim rData As Range 
Dim rng1 As Range 
Dim rng2 As Range 
Dim rcell As Range 
Dim lngCnt As Long 
Dim lngCalc As Long 

Set rData = Range("E11:G28,E33:G50,E57:G74,E79:G96,E101:G118,E130:G147,E152:G169,E175:G192,E198:G215,E221:G238") 

For Each rng1 In rData.Areas 
ltotal = ltotal + rData.Rows.Count 
Next 

With Application 
    .ScreenUpdating = False 
    .EnableEvents = False 
    lngCalc = .Calculation 
    .Calculation = xlCalculationManual 

    For Each rng2 In rData.Areas 
        For Each rcell In rng2.Rows 
            rcell.EntireRow.Hidden = (.CountBlank(rcell) = 3) 
            lngCnt = lngCnt + 1 
            .StatusBar = "Processing row " & lngCnt & "    " & Format((lngCnt / ltotal), "0%") 
        Next rcell 
    Next 


    .ScreenUpdating = True 
    .EnableEvents = True 
    .Calculation = lngCalc 
    .StatusBar = vbNullString 
End With 

End Sub  

answered Jun 9, 2014 at 10:53

brettdj's user avatar

brettdjbrettdj

54.6k16 gold badges113 silver badges176 bronze badges

5

Try this:

Sub Home()
    Dim cell As Range, N As Long
    For Each cell In Range("E11:G28,E33:G50,E57:G74,E79:G96,E101:G118,E130:G147,E152:G169,E175:G192,E198:G215,E221:G238").Areas
        N = N + cell.Cells.Count
    Next cell
    Debug.Print N
End Sub

This counts all the cells in your range.

answered Jun 9, 2014 at 10:10

L42's user avatar

L42L42

19.3k11 gold badges43 silver badges68 bronze badges

For example:

Dim rData As Range
Set rData = Range("E11:G28,E33:G50,E57:G74,E79:G96,E101:G118,E130:G147,E152:G169,E175:G192,E198:G215,E221:G238")
lTotal = rData.Count
For Each cell In rData.Cells
    Application.StatusBar = "Processing cell " & cell.AddressLocal & _
                                    "    " & Format((lCounter / lTotal), "0%")
    cell.EntireRow.Hidden = (cell.Value = "")
    lCounter = lCounter + 1
Next cell

answered Jun 9, 2014 at 10:10

Rory's user avatar

RoryRory

32.4k5 gold badges31 silver badges34 bronze badges

Try this —

Range(Selection.Address).Count

minocha's user avatar

minocha

1,0431 gold badge12 silver badges26 bronze badges

answered Jun 29, 2016 at 13:30

n3cao's user avatar

n3caon3cao

92 bronze badges

2

Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами 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.


Excel VBA Counter

There are various functions in MS Excel to count values, whether a string or numbers. Counting can be done based on some criteria. Functions in Excel include COUNT, 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
, COUNTBLANK, COUNTIFThe COUNTIF function in Excel counts the number of cells within a range based on pre-defined criteria. It is used to count cells that include dates, numbers, or text. For example, COUNTIF(A1:A10,”Trump”) will count the number of cells within the range A1:A10 that contain the text “Trump”
read more
, and COUNTIFS in excel”COUNTIFSread more. However, these functions cannot do some tasks like counting the cells based on their color, counting only bold values, etc. That is why we will create a counter in VBA to count these tasks in Excel.

Table of contents
  • Excel VBA Counter
    • Examples of Excel VBA Counter
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

VBA-Counter

Let us create some counters in Excel VBA.

Examples of Excel VBA Counter

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

Below are examples of the counter in VBA.

Example #1

VBA Counter Example 1

Suppose we have data like the above for 32 rows. First, we will create a VBA counter, which will count the values greater than 50 and one more counter to count the values less than 50. Then, we will create the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more so the user can have data for unlimited rows in Excel.

To do the same, the steps would be:

Make sure the Developer tab Excel is visible. To make the tab visible (if not), the steps are:

First, click on the ‘File’ tab in the ribbon and choose ‘Option’ from the list.

VBA Counter Example 1-1

Choose ‘Customize Ribbon’ from the list, check the box for ‘Developer,’ and click on OK.

VBA Counter Example 1-2

Now the ‘Developer’ tab is visible.

VBA Counter Example 1-3

Insert the command button using the ‘Insert’ command available in the ‘Controls’ group in the ‘Developer’ tab.

VBA Counter Example 1-4

While pressing the ALT key, create the command button with the mouse. Then, if we keep pressing the ALT key, the edges of the command button go automatically with the border of the cells.

VBA Counter Example 1-5

Right-click on the command button to open the contextual menu (make sure ‘Design Mode’ is activated; otherwise, we will not be able to open the contextual menu).

VBA Counter Example 1-6

Choose ‘Properties’ from the menu.

VBA Counter Example 1-7

Change the properties of the command button, i.e., Name, Caption, Font, etc.

VBA Counter Example 1-8

Right-click again and choose the ‘View Code’ from the contextual menu.

VBA Counter Example 1-9

Visual Basic Editor opens now. By default, it creates a subroutine for the command button.

VBA Counter Example 1-10

We will write code now. But, first, we will declare 3 variables. One for loop purposes, one to count, and one to store the value for the last row.

VBA Counter Example 1-11

We will use the code to select cell A1 and then the current region of cell A1 and then get down to the last filled row to get the last filled row number.

VBA Counter Example 1-12

We will run a ‘for’ loop in VBA to check the values written in the A2 cell to the last filled cell in the A column. We will increase the value of the ‘counter’ variable by 1 if the value is greater than 50 and will change the font color of the cell to ‘Blue,’ and if the value is less than 50, then the font color of the cell would be ‘Red.’

VBA Counter Example 1-13

After checking and counting, we need to display the values. To do the same, we will use VBA MsgBoxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.’

VBA Counter Example 1-14

Code:

Private Sub CountingCellsbyValue_Click()

Dim i, counter As Integer
Dim lastrow As Long

lastrow = Range("A1").CurrentRegion.End(xlDown).Row

For i = 2 To lastrow

If Cells(i, 1).Value > 50 Then
counter = counter + 1
Cells(i, 1).Font.ColorIndex = 5
Else
Cells(i, 1).Font.ColorIndex = 3
End If

Next i

MsgBox "There are " & counter & " values which are greater than 50" & _
vbCrLf & "There are " & lastrow - counter & " values which are less than 50"

End Sub

Deactivate the ‘Design Mode’ and click on the ‘Command button.’ The result would be as follows.

vba counter example 1

Example #2

Suppose we want to create the time counter using Excel VBA as follows:

Then, if we click on the ‘Start’ button, the timer starts, and if we click on the ‘Stop’ button, the timer stops.

To do the same, the steps would be:

First, create a format like this in an Excel sheet.

VBA Counter Example 2

Change the format of cell A2 to ‘hh:mm: ss.’

VBA Counter Example 2-1

Merge the cells C3 to G7 by using the Merge and Center ExcelThe merge and center button is used to merge two or more different cells. When data is inserted into any merged cells, it is in the center position, hence the name merge and center. read more command in the ‘Alignment’ group in the ‘Home’ tab.

VBA Counter Example 2-2

Give the reference of cell A2 for just merged cell and then do the formatting like make the font style to ‘Baskerville,’ font size to 60, etc.

VBA Counter Example 2-3

Create two command buttons, ‘Start’ and ‘Stop, using the ‘Insert’ command in the ‘Controls’ group in the ‘Developer’ tab.

VBA Counter Example 2-4

Change the properties using the ‘Properties’ command in the ‘Controls’ group in the ‘Developer’ tab.

VBA Counter Example 2-5

Select the commands buttons one by one and choose the ‘View Code’ command from the ‘Controls’ group in the ‘Developer’ tab to write the code as follows.

VBA Counter Example 2-6

Choose from the dropdown the appropriate command button.

VBA Counter Example 2-7

VBA Counter Example 2-8

Insert a module into ThisWorkbookVBA ThisWorkbook refers to the workbook on which the users currently write the code to execute all of the tasks in the current workbook. In this, it doesn’t matter which workbook is active and only requires the reference to the workbook, where the users write the code.read more by right-clicking on the ‘Thisworkbook, then choose ‘Insert’ and then ‘Module.’

Example 2-9

Write the following code in the module.

Code:

Sub start_time()
Application.OnTime Now + TimeValue("00:00:01"), "next_moment"
End Sub
Sub end_time()
Application.OnTime Now + TimeValue("00:00:01"), "next_moment", , False
End Sub

Sub next_moment()
If Worksheets("Time Counter").Range("A2").Value = 0 Then Exit Sub
Worksheets("Time Counter").Range("A2").Value = Worksheets("Time Counter").Range("A2").Value - TimeValue("00:00:01")
start_time
End Sub

We have used the ‘onTime‘ method of the Application object to run a procedure at a scheduled time. The procedure we have scheduled to run is “next_moment.”

Save the code. Write the time in the A2 cell and click on the ‘Start’ button to start the time counter.

vba counter example 2

Example #3

Suppose we have a list of students along with marks scored by them. We want to count the number of students who passed and who failed.

Example 3

To do the same, we will write the VBA code.

Steps would be:

Open Visual Basic Editor by pressing the shortcut in excelAn Excel shortcut is a technique of performing a manual task in a quicker way.read more Alt+F11 and double click on ‘Sheet3 (Counting Number of students)’ to insert a subroutine based on an event in Sheet3.

Example 3-1

Choose ‘Worksheet’ from the dropdown.

Example 3-2

As we pick ‘Worksheet’ from the list, we can see various events in the adjacent dropdown. But, first, we need to choose ‘SelectionChange’ from the list.

Example 3-3

Example 3-4

We will declare the VBA variableVariable 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 morelastrow’ for storing the last row number as a list for students can increase, ‘pass’ to store several students who passed, and ‘fail’ to store several students who failed.

Example 3-5

We will store the value of the last row number in ‘lastrow.’

Example 3-6

We will create the ‘for’ loop for counting based on condition.

Example 3-7

We have set the condition if the total marks are greater than 99, then add the value 1 to the ‘pass’ variable and add one value to the ‘fail’ variable if the condition fails.

The last statement makes the heading ‘Summary’ bold.

To print the values in the sheet, the code would be:

Example 3-8

Code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lastrow As Long
Dim pass As Integer
Dim fail As Integer

lastrow = Range("A1").CurrentRegion.End(xlDown).Row

For i = 2 To lastrow

If Cells(i, 5) > 99 Then
pass = pass + 1
Else
fail = fail + 1
End If
Cells(1, 7).Font.Bold = True

Next i

Range("G1").Value = "Summary"
Range("G2").Value = "The number of students who passed is " & pass
Range("G3").Value = "The number of students who failed is " & fail

End Sub

Now, whenever there is a selection change, values will be calculated again as below:

VBA Counter Example 3-9

Things to Remember

  1. Save the file after writing code in VBA with the .xlsm excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more. Otherwise, the macro will not work.
  2. We must use the ‘For’ loop when we have already decided how many times the code in the VBA loopA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more will run.

Recommended Articles

This article has been a guide to VBA Counter. Here, we discuss how we will create a counter in excel VBA to count cells based on color, counting only bold values, etc. Below you can find some useful Excel VBA articles: –

  • VBA With Statement
  • VBA DoEvents
  • VBA FreeFile
  • VBA COUNTA Function

Понравилась статья? Поделить с друзьями:
  • Cell contains excel if microsoft
  • Cell column number excel
  • Cell box in excel
  • Cell border excel vba
  • Cell begins with excel