Home » excel » count no of clicks on a button in excel vba

count no of clicks on a button in excel vba

Posted by: admin May 14, 2020 Leave a comment


I have a form control button which i want to use to group-ungroup columns.That is if it is clicked the first time it groups/hides those columns and next time it it clicked it unhides those columns.

I want to count the no of click on that button so that ,if the variable containing the no of clicks count is odd i will hide the columns else if it is even i will unhide the column.

this is my code

Private Sub CommandButton1_Click()
Static cnt As Long
cnt = 0
Dim remain As Integer
cnt = cnt + 1

remain = cnt Mod 2

If remain = 1 Then
 ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
 End If

 If remain = 2 Then
 ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
 End If

End Sub

So how can i count the no of clicks on that button in a variable in vba.
Sorry for the bad english?

How to&Answers:

Ok you do not need to use a count and keep adding to it. You can use a Boolean Variable instead. Here is an example. This works an an ON/OFF switch.

Option Explicit

Dim boolOn As Boolean

Sub CommandButton1_Click()
    If boolOn = False Then
        boolOn = True

        MsgBox "OFF"
        '~~> Do what you want to do
        boolOn = False
        '~~> Do what you want to do
        MsgBox "ON"
    End If
End Sub