VBA брояч - Как да създам брояч в Excel VBA? (с примери)

Съдържание

Excel VBA брояч

В MS Excel има различна функция за преброяване на стойности, независимо дали е низ, числа. Преброяването може да се извърши въз основа на някои критерии. Функциите включват COUNT, COUNTA, COUNTBLANK, COUNTIF и COUNTIFS в Excel. Тези функции обаче не могат да изпълняват някои задачи като преброяване на клетките въз основа на цвета им, преброяване само на получер шрифт и т.н. Ето защо ще създадем брояч във VBA, за да можем да преброим за тези типове задачи в Excel.

Нека създадем брояч в Excel VBA.

Примери за Excel VBA брояч

По-долу са дадени примери за брояча във VBA.

Пример # 1

Да предположим, че имаме данни като горе за 32 реда. Ще създадем VBA брояч, който ще отчита стойностите, които са по-големи от 50, и още един брояч, за да преброим стойностите, които са по-малки от 50. Ще създадем VBA кода по този начин, за да може потребителят да има данни за неограничени редове в Excel.

За да направите същото, стъпките ще бъдат:

Уверете се, че раздела за програмисти Excel е видим. За да направите раздела видим (ако не), стъпките са:

Кликнете върху раздела „Файл“ в лентата и изберете „Опция“ от списъка.

Изберете „ Персонализиране на лентата“ от списъка, поставете отметка в квадратчето за „Програмист“ и кликнете върху OK .

Сега се вижда раздела „Разработчик“ .

Поставете командния бутон, като използвате командата „Вмъкване“, налична в групата „Контроли“ в раздела „Програмист“ .

Докато натискате клавиша ALT , създайте командния бутон с мишката. Ако продължаваме да натискаме клавиша ALT , тогава ръбовете на командния бутон автоматично се съчетават с границата на клетките.

Щракнете с десния бутон на мишката върху командния бутон, за да отворите контекстното меню (уверете се, че е активиран „Режим на проектиране“ ; в противен случай няма да можем да отворим контекстното меню).

Изберете 'Properties' от менюто.

Променете свойствата на командния бутон, т.е. име, надпис и шрифт и т.н.

Щракнете с десния бутон отново и изберете „Преглед на кода“ от контекстното меню.

Редакторът на Visual Basic е отворен сега и по подразбиране вече е създадена подпрограма за командния бутон.

Ще напишем код сега. Ще декларираме 3 променливи. Един за целта, един за преброяване и един за съхраняване на стойността за последния ред.

Ще използваме кода, за да изберем клетка А1 и след това текущата област на клетка А1 и след това да стигнем до последния попълнен ред, за да получим номера на последния попълнен ред.

Ще стартираме цикъл „за“ във VBA, за да проверим стойностите, записани в клетката А2 до последната попълнена клетка в колона А. Ще увеличим стойността на променливата 'counter' с 1, ако стойността е по-голяма от 50 и ще променим цвета на шрифта на клетката на 'Blue', а ако стойността е по-малка от 50, тогава цвета на шрифта на клетката би било „червено“.

След проверка и преброяване трябва да покажем стойностите. За да направим същото, ще използваме „VBA MsgBox“.

Код:

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 Тогава counter = брояч + 1 клетки (i, 1) .Font.ColorIndex = 5 други клетки (i, 1) .Font.ColorIndex = 3 End If Next i MsgBox "Има" & брояч & "стойности, които са по-големи от 50" & _ vbCrLf & "Има" & lastrow - брояч & "стойности, които са по-малко от 50" End Sub

Деактивирайте „Режим на проектиране“ и кликнете върху „Команден бутон“. Резултатът ще бъде както следва.

Пример # 2

Да предположим, че искаме да създадем брояч на времето, използвайки Excel VBA, както следва:

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.

Интересни статии...