vba 计算excel vba中按钮的点击次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20272202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:42:36  来源:igfitidea点击:

count no of clicks on a button in excel vba

excelvbaexcel-vba

提问by shiven

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 variablecontaining the no of clickscount is oddi will hide the columns else if it is eveni will unhide the column.

我想计算点击该按钮variableno of clicks次数,以便,如果包含计数是odd我将隐藏列,否则even我将取消隐藏该列。

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?

那么我如何计算 vba 变量中该按钮的点击次数。抱歉英语不好?

回答by Siddharth Rout

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

好的,您不需要使用计数并继续添加它。您可以改用Boolean变量。这是一个例子。这是一个ON/OFF开关。

Option Explicit

Dim boolOn As Boolean

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

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