Make vba code work for all boxes

前端 未结 4 782
攒了一身酷
攒了一身酷 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:56

    In case you do not know, all Form Controls are treated as Shapes in a Worksheet.

    I have a solution that you need to create a new Module, copy-paste in code below and then from Immediate window to the same module. With some assumptions:

    • All Check Box Objects are named "Check Box #" where # is a number
    • No macro named ResetCheckBoxes() in any other modules of the workbook
    • No macro named CheckBox#_Click() in any other modules of the workbook

    Run this ResetCheckBoxes once to enable check boxes and Assign a macro to it for you, with relevant generated codes in the immediate window (you might want to put a pause in the loop every 25 check boxes as line buffer in it are limited).

    Sub ResetCheckBoxes()
        Dim oWS As Worksheet, oSh As Shape, sTmp As String
    
        Set oWS = ThisWorkbook.ActiveSheet
        For Each oSh In oWS.Shapes
            With oSh
                If .Type = msoFormControl Then
                    If InStr(1, .Name, "Check Box", vbTextCompare) = 1 Then
                        .ControlFormat.Enabled = True
                        sTmp = "CheckBox" & Replace(oSh.Name, "Check Box ", "") & "_Click"
                        .OnAction = sTmp
                        Debug.Print "Sub " & sTmp & "()"
                        Debug.Print vbTab & "ActiveSheet.Shapes(""" & .Name & """).ControlFormat.Enabled = False"
                        Debug.Print "End Sub" & vbCrLf
                    End If
                End If
            End With
        Next
    End Sub
    

    Example Immediate window output (2 test check boxes): GeneratedCodes

    Happy New Year mate!

提交回复
热议问题