Contatore VBA - Come creare un contatore in Excel VBA? (con esempi)

Contatore VBA di Excel

Ci sono le varie funzioni in MS Excel per contare i valori, sia che si tratti di una stringa, di numeri. Il conteggio può essere eseguito in base ad alcuni criteri. Le funzioni includono COUNT, COUNTA, COUNTBLANK, COUNTIF e COUNTIFS in Excel. Tuttavia, queste funzioni non possono eseguire alcune attività come contare le celle in base al loro colore, contare solo valori in grassetto, ecc. Ecco perché creeremo un contatore in VBA in modo da poter contare per questi tipi di attività in Excel.

Creiamo un contatore in Excel VBA.

Esempi di contatore VBA di Excel

Di seguito sono riportati esempi del contatore in VBA.

Esempio 1

Supponiamo di avere dati come sopra per 32 righe. Creeremo un contatore VBA, che conterà i valori, che sono maggiori di 50 e un contatore in più per contare i valori, che sono inferiori a 50. Creeremo il codice VBA in questo modo in modo che l'utente possa avere dati per righe illimitate in Excel.

Per fare lo stesso, i passaggi sarebbero:

Assicurati che la scheda Sviluppo di Excel sia visibile. Per rendere visibile la scheda (in caso contrario), i passaggi sono:

Fare clic sulla scheda "File" nella barra multifunzione e scegliere "Opzione" dall'elenco.

Scegli " Personalizza barra multifunzione" dall'elenco, seleziona la casella "Sviluppatore" e fai clic su OK .

Ora la scheda "Sviluppatore" è visibile.

Inserisci il pulsante di comando utilizzando il comando "Inserisci" disponibile nel gruppo "Controlli" nella scheda "Sviluppatore" .

Mentre si preme il tasto ALT , creare il pulsante di comando con il mouse. Se continuiamo a premere il tasto ALT , i bordi del pulsante di comando vanno automaticamente con il bordo delle celle.

Fare clic con il pulsante destro del mouse sul pulsante di comando per aprire il menu contestuale (assicurarsi che la "Modalità di progettazione" sia attivata, altrimenti non saremo in grado di aprire il menu contestuale).

Scegli "Proprietà" dal menu.

Modificare le proprietà del pulsante di comando, ad esempio Nome, Didascalia e Carattere, ecc.

Fare nuovamente clic con il pulsante destro del mouse e scegliere "Visualizza codice" dal menu contestuale.

Visual Basic Editor è ora aperto e, per impostazione predefinita, una subroutine è già creata per il pulsante di comando.

Scriveremo ora il codice. Dichiareremo 3 variabili. Uno per lo scopo del ciclo, uno per contare e uno per memorizzare il valore per l'ultima riga.

Useremo il codice per selezionare la cella A1 e quindi la regione corrente della cella A1, quindi scenderemo all'ultima riga piena per ottenere l'ultimo numero di riga riempito.

Eseguiremo un ciclo "for" in VBA per controllare i valori scritti nella cella A2 nell'ultima cella riempita nella colonna A. Aumenteremo il valore della variabile "counter" di 1 se il valore è maggiore di 50 e cambieremo il colore del carattere della cella in "Blu", e se il valore è inferiore a 50, il colore del carattere della cella sarebbe "Rosso".

Dopo aver controllato e contato, dobbiamo visualizzare i valori. Per fare lo stesso, useremo "VBA MsgBox".

Codice:

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 "Sono presenti" & counter & "valori maggiori di 50" & _ vbCrLf & "Ci sono" & lastrow - counter & "valori inferiori a 50" End Sub

Disattiva la "Modalità di progettazione" e fai clic sul pulsante "Comando". Il risultato sarebbe il seguente.

Esempio n. 2

Supponiamo di voler creare il contatore del tempo utilizzando Excel VBA come segue:

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.

Articoli interessanti...