VBA számláló - Hogyan készítsünk számlálót az Excel VBA-ban? (példákkal)

Tartalomjegyzék

Excel VBA számláló

Az MS Excel különféle funkcióval számolhatja az értékeket, legyen szó karakterláncról vagy számokról. A számlálás néhány kritérium alapján elvégezhető. A funkciók között szerepel a COUNT, a COUNTA, a COUNTBLANK, a COUNTIF és a COUNTIFS az excelben. Ezek a függvények azonban nem tudnak olyan feladatokat végrehajtani, mint például a cellák számlálása a színük alapján, csak a vastag értékek megszámlálása stb. Ezért hozunk létre egy számlálót a VBA-ban, hogy az ilyen típusú feladatokkal számolhassunk az excelben.

Hozzunk létre néhány számlálót az excel VBA-ban.

Példák az Excel VBA számlálóra

Az alábbiakban bemutatunk példákat a VBA számlálójára.

1. példa

Tegyük fel, hogy 32 fentihez hasonló adatokkal rendelkezünk. Létrehozunk egy VBA számlálót, amely megszámolja az 50-nél nagyobb értékeket, és még egy számlálót az 50-nél kisebb értékek számlálásához. A VBA kódot ily módon hozzuk létre, hogy a felhasználó rendelkezzen adatokkal korlátlan sor az excelben.

Ugyanez a lépés a következő:

Győződjön meg arról, hogy a Fejlesztő lap Excel látható. A fül láthatóvá tételéhez (ha nem), a következőkre van szükség:

Kattintson a szalag "Fájl" fülére, és válassza a listából az "Option" lehetőséget .

Válassza ki a " Customize Ribbon" lehetőséget a listából, jelölje be a "Developer" jelölőnégyzetet , és kattintson az OK gombra .

Most látható a „Fejlesztő” fül .

Helyezze be a parancsgombot a „Fejlesztő” fül „Vezérlők” csoportjában elérhető „Beszúrás” paranccsal .

Az ALT gomb lenyomása közben hozza létre a parancsgombot az egérrel. Ha folyamatosan nyomjuk meg az ALT gombot , akkor a parancs gomb élei automatikusan mennek a cellák határával.

Kattintson a jobb gombbal a parancsgombra a kontextuális menü megnyitásához (ellenőrizze, hogy a „Tervezési mód” be van-e kapcsolva; különben nem tudjuk megnyitni a kontextuális menüt).

Válassza a menü „Tulajdonságok” elemét.

Módosítsa a parancs gomb tulajdonságait, pl. Név, Felirat, Betűtípus stb.

Kattintson a jobb gombbal újra, és válassza a „Kód megtekintése” lehetőséget a kontextuális menüből.

A Visual Basic Editor most megnyílt, és alapértelmezés szerint már létrehozott egy alprogramot a parancsgombhoz.

Most kódot írunk. 3 változót fogunk deklarálni. Egy ciklus céljára, egy számolásra és egy az utolsó sor értékének tárolására.

A kód segítségével kiválasztjuk az A1 cellát, majd az A1 cella aktuális régióját, majd lejutunk az utolsó kitöltött sorra, hogy megkapjuk az utolsó kitöltött sorszámot.

Futtatunk egy „for” ciklust a VBA-ban, hogy ellenőrizzük az A2 cellában az A oszlop utolsó kitöltött cellájába írt értékeket. 1-gyel növeljük a 'számláló' változó értékét, ha az érték nagyobb, mint 50, és a cella betűtípusának színét kékre változtatjuk , és ha az értéke 50-nél kisebb, akkor a cella betűtípusának színe vörös lenne .

Ellenőrzés és számlálás után meg kell jelenítenünk az értékeket. Ehhez a 'VBA MsgBox' fájlt fogjuk használni .

Kód:

Privát alszámlálásCellsbyValue_Click () Dim i, számláló, mint Integer Dim, olyan hosszú, mint Last Longrow = Tartomány ("A1"). CurrentRegion.End (xlDown). Sor az i = 2 számára, ha a cellák (i, 1). Érték> 50, majd számláló = számláló + 1 cella (i, 1) .Font.ColorIndex = 5 egyéb cella (i, 1) .Font.ColorIndex = 3 vége, ha Következő i MsgBox "Vannak" & számláló & "értékek, amelyek nagyobbak, mint 50" & _ vbCrLf & "Vannak" & lastrow - counter & "értékek, amelyek kisebbek, mint 50" End Sub

Deaktiválja a "Tervezési mód" elemet, és kattintson a "Parancs gombra". Az eredmény a következő lenne.

2. példa

Tegyük fel, hogy az excel VBA használatával szeretnénk létrehozni az időszámlálót az alábbiak szerint:

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.

érdekes cikkek...