多个命令按钮

问题描述 投票:0回答:2

我正在制作一张纸,以帮助数独,并具有从1 t0 9开始的命令按钮,按下该按钮时,该按钮从数字变为空白。每个按钮的代码为:-

Private Sub CommandButton1_Click()
If CommandButton1.Caption = "1" Then CommandButton1.Caption = "" Else CommandButton1.Caption = "1"
End Sub

Private Sub CommandButton2_Click()
If CommandButton2.Caption = "2" Then CommandButton2.Caption = "" Else CommandButton2.Caption = "2"
End Sub

Private Sub CommandButton3_Click()
If CommandButton3.Caption = "3" Then CommandButton3.Caption = "" Else CommandButton3.Caption = "3"
End Sub

Private Sub CommandButton4_Click()
If CommandButton4.Caption = "4" Then CommandButton4.Caption = "" Else CommandButton4.Caption = "4"
End Sub

Private Sub CommandButton5_Click()
If CommandButton5.Caption = "5" Then CommandButton5.Caption = "" Else CommandButton5.Caption = "5"
End Sub

Private Sub CommandButton6_Click()
If CommandButton6.Caption = "6" Then CommandButton6.Caption = "" Else CommandButton6.Caption = "6"
End Sub

Private Sub CommandButton7_Click()
If CommandButton7.Caption = "7" Then CommandButton7.Caption = "" Else CommandButton7.Caption = "7"
End Sub

Private Sub CommandButton8_Click()
If CommandButton8.Caption = "8" Then CommandButton8.Caption = "" Else CommandButton8.Caption = "8"
End Sub

Private Sub CommandButton9_Click()
If CommandButton9.Caption = "9" Then CommandButton9.Caption = "" Else CommandButton9.Caption = "9"
End Sub

我想复制并越过这9个按钮,并将代码保留在命令按钮中,但是在代码中更改按钮编号,但其余代码保持相同。那可能吗。

Private Sub CommandButton10_Click()
If CommandButton1.Caption = "1" Then CommandButton1.Caption = "" Else CommandButton1.Caption = "1"
End Sub
excel vba button command
2个回答
0
投票

您可以为此创建一个class resp. control array,但可能最简单的方法就是使用下面的Sub

Sub chCaption(newCaption As String, ctrl As MSForms.Control)
    With ctrl
        If .Caption = newCaption Then
            .Caption = ""
        Else
            .Caption = newCaption
        End If
    End With
End Sub

那样

Private Sub CommandButton1_Click()
    chCaption "1", Me.CommandButton1
End Sub

Private Sub CommandButton2_Click()
    chCaption "2", Me.CommandButton2
End Sub

0
投票

我相信下面的代码将满足您的要求。根据需要仅从一个或多个表中进行调用,就可以按需在其中具有命令按钮的代码表中进行安装,也可以将其公开,然后将其安装在标准代码模块中。

Private Sub ResetButton(ByVal Id As Integer)
    ' 028

    Dim BtnVal As Integer

    BtnVal = Id Mod 9
    If BtnVal = 0 Then BtnVal = 9

    With ActiveSheet.OLEObjects("CommandButton" & Id).Object
        .Caption = IIf(Len(.Caption), "", BtnVal)
    End With
End Sub

此代码通过使用MOD功能从CommandButton编号中提取Soduko编号。 CommandButtons1到9将保存数字1到9,10到18、19到27等。对于每个按钮,您需要一个类似下面的过程才能在工作表的代码模块中显示。

Private Sub CommandButton1_Click()
    ' 028
    ResetButton 1
End Sub

每个副本中的参数都是不同的,与它响应的CommandButton的编号相同。

虽然这应该做您应该做的事情

© www.soinside.com 2019 - 2024. All rights reserved.