0

VBA masters,

I have an Excel Userform that has a frame called studentFrame. In that frame, I am programmatically creating buttons with the following code:


nCheckTopPosition = 30
nLabelTopPositionName = 30
nLabelTopPositionGoal = 30

nNoOfCheckBoxes = mySht.Cells(mySht.Rows.Count, "A").End(xlUp).Row

For nControlIndex = 1 To nNoOfCheckBoxes

    Dim chkBox As Control

    Set chkBox = screen3Form.studentFrame.Controls.Add("Forms.CommandButton.1", "chkCheck" & nControlIndex, True)
    
    chkBox.Left = 12
    chkBox.Width = 30
    chkBox.Height = 18
    chkBox.Caption = "GAO"
    chkBox.Top = nCheckTopPosition
    nCheckTopPosition = nCheckTopPosition + 30

Next

When I run the userform, I now need to capture which of these buttons is pressed and execute more code. How can I accomplish this? There can be anywhere from 1 to 100 buttons being created.

  • https://www.encodedna.com/excel/how-to-add-events-to-dynamically-created-controls-in-excel-using-vba.htm – Tragamor Oct 27 '20 at 18:40
  • Try this. Add class :Public WithEvents oControl As MSForms.CommandButton Private Sub oControl_Click() MsgBox "Name: " & oControl.Name & Chr(13) & "Caption: " & oControl.Caption '//You can use select case here End Sub . Include in your code: Dim oEvent() As New Class1(declared globally) , and below your code : Dim objCount, counter As Integer objCount = studentFrame.Controls.Count ReDim oEvent(objCount) For counter = 0 To objCount - 1 Set oEvent(counter).oControl = studentFrame.Controls(counter) Next counter – Joel Oct 27 '20 at 20:43

0 Answers0