Contador de VBA - ¿Cómo crear un contador en Excel VBA? (con ejemplos)

Tabla de contenido

Contador de Excel VBA

Existen varias funciones en MS Excel para contar valores, ya sea una cadena, números. El recuento se puede realizar según algunos criterios. Las funciones incluyen COUNT, COUNTA, COUNTBLANK, COUNTIF y COUNTIFS en Excel. Sin embargo, estas funciones no pueden hacer algunas tareas como contar las celdas en función de su color, contar solo valores en negrita, etc. Es por eso que crearemos un contador en VBA para que podamos contar este tipo de tareas en Excel.

Creemos algún contador en Excel VBA.

Ejemplos de contador VBA de Excel

A continuación se muestran ejemplos del contador en VBA.

Ejemplo 1

Supongamos que tenemos datos como el anterior para 32 filas. Crearemos un contador VBA, que contará los valores, que sean mayores a 50 y un contador más para contar los valores, que sean menores a 50. Crearemos el código VBA de esta forma para que el usuario pueda tener datos para filas ilimitadas en Excel.

Para hacer lo mismo, los pasos serían:

Asegúrese de que la pestaña Desarrollador Excel esté visible. Para que la pestaña sea visible (si no es así), los pasos son:

Haga clic en la pestaña 'Archivo' en la cinta y elija 'Opción' de la lista.

Elija ' Personalizar cinta' de la lista, marque la casilla de 'Desarrollador' y haga clic en Aceptar .

Ahora la pestaña 'Desarrollador' está visible.

Inserte el botón de comando usando el comando 'Insertar' disponible en el grupo 'Controles' en la pestaña 'Desarrollador' .

Mientras presiona la tecla ALT , cree el botón de comando con el mouse. Si seguimos presionando la tecla ALT , los bordes del botón de comando van automáticamente con el borde de las celdas.

Haga clic con el botón derecho en el botón de comando para abrir el menú contextual (asegúrese de que el 'Modo de diseño' esté activado; de lo contrario, no podremos abrir el menú contextual).

Elija 'Propiedades' en el menú.

Cambie las propiedades del botón de comando, es decir, Nombre, Título y Fuente, etc.

Haga clic derecho nuevamente y elija 'Ver código' en el menú contextual.

El Editor de Visual Basic se abre ahora y, de forma predeterminada, ya se crea una subrutina para el botón de comando.

Escribiremos código ahora. Declararemos 3 variables. Uno para el propósito de bucle, uno para contar y otro para almacenar el valor de la última fila.

Usaremos el código para seleccionar la celda A1 y luego la región actual de la celda A1 y luego bajaremos a la última fila completa para obtener el último número de fila completa.

Ejecutaremos un ciclo 'for' en VBA para verificar los valores escritos en la celda A2 hasta la última celda llena en la columna A. Incrementaremos el valor de la variable 'contador' en 1 si el valor es mayor que 50 y cambiaremos el color de fuente de la celda a 'Azul', y si el valor es menor que 50, entonces el color de fuente de la celda sería 'Rojo'.

Después de verificar y contar, necesitamos mostrar los valores. Para hacer lo mismo, usaremos 'VBA MsgBox'.

Código:

Private Sub CountingCellsbyValue_Click () Dim i, counter As Integer Dim lastrow As Long lastrow = Range ("A1"). CurrentRegion.End (xlDown) .Row For i = 2 To lasttrow If Cells (i, 1) .Value> 50 Then contador = contador + 1 Celdas (i, 1) .Font.ColorIndex = 5 Else Celdas (i, 1) .Font.ColorIndex = 3 End If Next i MsgBox "Hay" valores de & counter & "que son mayores que 50" & _ vbCrLf & "Hay" & lastrow - contador & "valores inferiores a 50" End Sub

Desactive el "Modo de diseño" y haga clic en el "Botón de comando". El resultado sería el siguiente.

Ejemplo # 2

Supongamos que queremos crear el contador de tiempo usando Excel VBA de la siguiente manera:

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, steps would be:

Create a format like this in an excel sheet.

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

Merge the cells C3 to G7 by using the Merge and Center Excel command in the ‘Alignment’ group in the ‘Home’ tab.

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.

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

Using the ‘Properties’ command available in the ‘Controls’ group in the ‘Developer’ tab, change the properties.

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.

Choose from the drop-down the appropriate command button.

Insert a module into ‘ThisWorkbook‘ by right-clicking on the ‘Thisworkbook’ and then choose ‘Insert’ and then ‘Module.’

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, which is used to run a procedure at a scheduled time. The procedure, which 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.

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.

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

Steps would be:

Open Visual Basic editor by pressing shortcut in excel Alt+F11 and double click on ‘Sheet3 (Counting Number of students)’ to insert a subroutine based on an event in Sheet3.

Choose ‘Worksheet’ from the dropdown.

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

We will declare the VBA variable ‘lastrow’ for storing last row number as a list for students can increase, ‘pass’ to store a number of students who passed, and ‘fail’ to store a number of students who failed.

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

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

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:

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 change in selection, values will be calculated again as below:

Things to Remember

  1. Save the file after writing code in VBA with .xlsm excel extension; otherwise, the macro will not work.
  2. Use the ‘For’ loop when it is decided already for how many times the code in the VBA loop will run.

Articulos interesantes...