VBA Counter

Last Updated :

-

Blog Author :

Edited by :

Reviewed by :

Table Of Contents

arrow

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, COUNTA, COUNTBLANK, COUNTIF, and COUNTIFS in excel. 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.

VBA-Counter

Let us create some counters in Excel VBA.

Examples of Excel VBA Counter

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 code 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 MsgBox.'

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 Excel 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 'ThisWorkbook' 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 excel 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 variable ā€˜lastrowā€™ 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 extension. 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 loop will run.