工作表上的多个切换按钮可触发宏

时间:2017-07-11 22:52:11

标签: excel vba excel-vba

我有20个切换按钮设置,如

Public Sub ToggleButton1_Click()
    Check_All
    If ToggleButton1.value = True Then
        ToggleButton1.BackColor = vbGreen
    Else:
        ToggleButton1.BackColor = vbRed
    End If
End Sub
Public Sub ToggleButton2_Click()
    Check_All
    If ToggleButton2.value = True Then
        ToggleButton2.BackColor = vbGreen
        Else:
        ToggleButton2.BackColor = vbRed
    End If
End Sub

我试图通过application.onkey触发它们,如:

Application.OnKey "%a", "Sheet1.ToggleButton1_Click"
Application.OnKey "%b", "Sheet1.ToggleButton2_Click"

当所有按钮都为“True”时使用Check_all,它将执行以下操作,以便在触发另一个“宏”之前将切换按钮恢复为“False”状态。

Sub Check_All()
    Dim tb As Object

    For Each tb In Me.OLEObjects
        If tb.ProgId = "Forms.ToggleButton.1" Then
            If tb.Object.value <> True Then Exit Sub
        End If
    Next

    CommandButton0_Click
End Sub
Private Sub CommandButton0_Click()
    Dim x As Integer

    For x = 1 To 20
        Worksheets("Sheet1").OLEObjects("ToggleButton" & x).Object.value = False
    Next x
    CommandButton3_Click
End Sub

但我似乎无法让application.onkey工作,我现在完全迷失了。

这是一个连接到可编程USB按钮的系统,我真的依赖于onkey来运行,除非有更好的方法???

1 个答案:

答案 0 :(得分:3)

您可以将宏指定给excel中的快捷键。你需要像这样模拟切换按钮点击:

Sub CtrlShiftA()
ToggleButton1.Value = Not ToggleButton1.Value
End Sub

然后根据需要设置切换按钮:

Private Sub ToggleButton1_Click()
If ToggleButton1.Value = True Then
    ToggleButton1.BackColor = vbGreen
Else
    ToggleButton1.BackColor = vbRed
End If
End Sub

然后在View - &gt;下宏 - &gt;查看宏单击选项..:

enter image description here

Shift + ACtrl + Shift + A作为快捷键:

enter image description here

现在点击确定,享受你的shurtcut键。