Make vba code work for all boxes

前端 未结 4 781
攒了一身酷
攒了一身酷 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 12:07

    The easy way is to write a class module that will apply one code routine to a collection of Checkboxes

    Assuming yu want to run this on all ActiveX checkboxes on the ActiveSheet, then borrowing heavily from Bob Phillip's code from VBAX

    1. Insert a Class Module named clsActiveXEvents

      Option Explicit

      Public WithEvents mCheckboxes As MSForms.CheckBox
      
      Private Sub mCheckboxes_Click()
        mCheckboxes.Enabled = (MsgBox("Do you want to lock this box?", vbYesNo, "Warning") = vbNo)
      End Sub
      
    2. In a normal module use this code

      Dim mcolEvents As Collection
      
      Sub Test()
      Dim cCBEvents As clsActiveXEvents
      Dim shp As Shape
      
      Set mcolEvents = New Collection
      
      For Each shp In ActiveSheet.Shapes
          If shp.Type = msoOLEControlObject Then
              If TypeName(shp.OLEFormat.Object.Object) = "CheckBox" Then
                 Set cCBEvents = New clsActiveXEvents
                 Set cCBEvents.mCheckboxes = shp.OLEFormat.Object.Object
              mcolEvents.Add cCBEvents
          End If
      End If
      Next
      End Sub
      

提交回复
热议问题