I have been developing various reports and forms for data we are currently pulling from a legacy system. I have created a form that dynamically creates buttons and spaces them according to how many buttons have been created. My error comes in where I attempt to add _Click() functionality for each button, as the code will be unique for each button created. I have tried everything I can come up with and everything I have been able to find online, all to no avail. Through various different attempts, I have gotten to points where I have the buttons and the code populated in the UserForm CodeModule, but the _Click() event would not trigger from there. Any help would be greatly appreciated.
Private Sub CommandButton5_Click()
Dim lastrow As Long, i As Integer, numButtons As Integer, newButton As Control, lineNum As Long
numButtons = 1
With Sheets("Production Capacity")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("A4:AD" & lastrow).Interior.Color = RGB(255, 255, 255)
For i = 4 To lastrow
If i Mod 4 = 0 Then
If .Cells(i, "D").Value > .Cells(2, "G").Value Then
.Cells(i, "G").Interior.Color = RGB(255, 0, 0)
Set newButton = Me.Controls.Add("Forms.CommandButton.1", "button" & numButtons, False)
With newButton
.Width = 200
Select Case (numButtons Mod 3)
Case 0
.Left = 475
Case 1
.Left = 25
Case 2
.Left = 250
End Select
.Visible = True
.Height = 20
.Top = 60 + (Int((numButtons - 1) / 3) * 40)
.Caption = Sheets("Production Capacity").Cells(i, "A").Value & " - " & Sheets("Production Capacity").Cells(i, "B").Value & " DeptName"
.Font.Size = 10
.Font.Bold = True
End With
With ActiveWorkbook.VBProject.VBComponents("Class1").CodeModule
lineNum = .CreateEventProc("Click", "button" & numButtons) + 1 'This line is where the error occurs.
.InsertLines lineNum, _
"Dim lastrow as Long" & Chr(13) & _
"with Sheets(Sheets(""Production Capacity"").cells(1, ""A"").value)" & Chr(13) & _
".ShowAllData" & Chr(13) & _
"lastrow = .Cells(Rows.Count, ""B"").End(xlUp).Row" & Chr(13) & _
".Range(""A$6:$BQ$"" & lastrow).AutoFilter field:=30, Criteria1:=" & Chr(34) & ">=" & Chr(34) & " & " & Chr(34) & DateValue(Sheets("Production Capacity").Cells(i, "A").Value) & Chr(34) & ", Operator:=xlAnd, Criteria2:=" & Chr(34) & "<=" & Chr(34) & " & " & Chr(34) & DateValue(Sheets("Production Capacity").Cells(i, "B").Value) & Chr(34) & ", Operator:=xlAnd" & Chr(13) & _
"End With"
End With
numButtons = numButtons + 1
End If
The error is 'Run-time error '57017': Event handler is invalid
on this line: lineNum = .CreateEventProc("Click", "button" & numButtons) + 1