Kaunter VBA - Bagaimana Membuat Kaunter di Excel VBA? (dengan Contoh)

Isi kandungan

Kaunter VBA Excel

Terdapat pelbagai fungsi dalam MS Excel untuk menghitung nilai, sama ada rentetan, nombor. Pengiraan dapat dilakukan berdasarkan beberapa kriteria. Fungsi merangkumi COUNT, COUNTA, COUNTBLANK, COUNTIF, dan COUNTIFS dalam excel. Walau bagaimanapun, fungsi-fungsi ini tidak dapat melakukan beberapa tugas seperti menghitung sel berdasarkan warnanya, hanya menghitung nilai tebal, dan lain-lain. Itulah sebabnya kami akan membuat penghitung di VBA sehingga kami dapat mengira jenis tugas ini di excel.

Mari kita buat beberapa kaunter di excel VBA.

Contoh Kaunter VBA Excel

Berikut adalah contoh kaunter di VBA.

Contoh # 1

Katakan kita mempunyai data seperti di atas untuk 32 baris. Kami akan membuat pembilang VBA, yang akan menghitung nilai, yang lebih besar daripada 50 dan satu lagi pembilang untuk menghitung nilai, yang kurang dari 50. Kami akan membuat kod VBA dengan cara ini supaya pengguna dapat memiliki data untuk barisan tanpa had dalam excel.

Untuk melakukan perkara yang sama, langkah-langkahnya adalah:

Pastikan tab Pembangun Excel kelihatan. Untuk menjadikan tab kelihatan (jika tidak), langkah-langkahnya adalah:

Klik pada tab 'File' di pita dan pilih 'Option' dari senarai.

Pilih ' Customize Ribbon' dari senarai, tandakan kotak untuk 'Developer', dan klik OK .

Kini tab 'Pembangun' dapat dilihat.

Masukkan butang arahan menggunakan perintah 'Sisipkan' yang tersedia dalam kumpulan 'Kawalan' di tab 'Pembangun' .

Sambil menekan kekunci ALT , buat butang arahan dengan tetikus. Sekiranya kita terus menekan kekunci ALT , maka tepi butang arahan akan bergerak secara automatik dengan sempadan sel.

Klik kanan pada butang arahan untuk membuka menu kontekstual (pastikan 'Design Mode' diaktifkan; jika tidak, kita tidak akan dapat membuka menu kontekstual).

Pilih 'Properties' dari menu.

Tukar sifat butang arahan, iaitu, Name, Caption, dan Font, dll.

Klik kanan sekali lagi dan pilih 'Lihat Kod' dari menu kontekstual.

Visual Basic Editor dibuka sekarang, dan secara lalai, subrutin telah dibuat untuk butang arahan.

Kami akan menulis kod sekarang. Kami akan menyatakan 3 pemboleh ubah. Satu untuk tujuan gelung, satu untuk dikira, dan satu untuk menyimpan nilai untuk baris terakhir.

Kami akan menggunakan kod untuk memilih sel A1 dan kemudian kawasan sel A1 terkini dan kemudian turun ke baris terakhir yang diisi untuk mendapatkan nombor baris terakhir yang diisi.

Kami akan menjalankan gelung 'untuk' di VBA untuk memeriksa nilai yang ditulis dalam sel A2 ke sel yang terakhir diisi di lajur A. Kami akan meningkatkan nilai pemboleh ubah 'penghitung' sebanyak 1 jika nilainya lebih besar dari 50 dan akan mengubah warna fon sel menjadi 'Biru', dan jika nilainya kurang dari 50, maka warna fon sel akan menjadi 'Merah.'

Setelah memeriksa dan mengira, kita perlu memaparkan nilai. Untuk melakukan perkara yang sama, kami akan menggunakan 'VBA MsgBox.'

Kod:

Sub Counting SwastaCellsbyValue_Click () Dim i, counter As Integer Dim lastrow As Long Lastrow = Range ("A1"). CurrentRegion.End (xlDown). Baris untuk i = 2 Untuk terakhir jika Cell (i, 1). Nilai> 50 Kemudian pembilang = pembilang + 1 Sel (i, 1). Font.ColorIndex = 5 Sel Lain (i, 1) .Font.ColorIndex = 3 Tamat Jika Seterusnya i MsgBox "Terdapat nilai" & kaunter & "yang lebih besar daripada 50" & _ vbCrLf & "Terdapat" & lastrow - pembilang & "nilai yang kurang daripada 50" Sub Akhir

Nyahaktifkan 'Design Mode' dan klik pada 'Command button'. Hasilnya adalah seperti berikut.

Contoh # 2

Andaikan kita ingin membuat penghitung waktu menggunakan excel VBA seperti berikut:

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.

Artikel menarik...