多个命令按钮

我正在制作一张纸,以帮助数独,并具有从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
评论
zrerum
zrerum

You could create a class resp. control array (also a good example here) for that but possibly the easiest way for you is just to use the following 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
点赞
评论
琴心
琴心

我相信下面的代码将满足您的要求。将其按需安装在具有命令按钮的代码表中原样安装,或者将其公开并安装在标准代码模块中,具体取决于您是需要从一个工作表中调用还是从多个工作表中进行调用。

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的编号相同。

虽然这应该做你所要做的

点赞
评论