Make vba code work for all boxes

前端 未结 4 813
攒了一身酷
攒了一身酷 2021-01-21 11:33

Hello so what i want to do is make this code work for all Check Box\'s 1-50 I want the code to only effect the box that is clicked.

Private Sub CheckBox1_Click()         


        
4条回答
  •  轮回少年
    2021-01-21 11:48

    I see several options (none of which are pretty since this is VBA).

    • Option 1: generate the code for all of your check boxes. This is probably the most maintainable. You would first choose reasonable names for all your check boxes (you can assign them by selecting them in Excel and renaming in the top left corner, or run code which will do this for you if you already have a lot of check boxes. This may be useful).

      You can then generate the code and have each one of your subprocedues as follows:

      'example code for one checkbox
      Private Sub chkBox_1_Click()
          Call lockMeUp(Sheet1.chkBox_1.Object)
      End Sub
      

      After you're done with all your code for each checkbox, you could have your lockMeUp subprocedure as follows:

      Sub lockMeUp(chkBox as Object)
          If MsgBox("Do you want to lock this box?", vbYesNo, "Warning") = vbYes Then
              chkBox.Enabled = False
          End If
      End Sub
      
    • Option 2: Keep track of all your checked/unchecked statuses through either an Array or a "Settings" hidden sheet, and watch out for that triggered event. You could fire off based off of a sheet's Changed event, and match the row number to your CheckBox number so that you can go off of the Target's row number.

    Other options I can think of become more convoluted... I'd be interested to see what other suggestions people have. Thanks!

    EDIT You can use some code to refer to a single function as in my example, in conjunction with brettdj's example to get your optimal solution. Bam!

提交回复
热议问题