Hello chucklod,
I made the needed changes to code to make it work. You were very close to having it work. I am including the macros here for the other members to see.
Option Explicit
Public TestForm
Public AddEventProcButton
Public TestEventProcButton
Sub DoDataPoints()
'
Dim N As Long
Dim LineCount
Dim MacroString As String
' Create the base form
Set TestForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
With TestForm
.Properties("Top") = 0
.Properties("Left") = 0
.Properties("Height") = 85
.Properties("Width") = 240
.Properties("Caption") = "Test Form"
.Properties("StartUpPosition") = 2
End With
' Create the button which will add the other button
Set AddEventProcButton = TestForm.Designer.Controls.Add("forms.CommandButton.1")
With AddEventProcButton
.Name = "AddEventProcButton"
.Caption = "Add Event Proc"
.Height = 24
.Width = 66
.Left = 36
.Top = 18
End With
' Create the event handlers
N = TestForm.CodeModule.CreateEventProc("Terminate", "UserForm")
MacroString = _
vbCrLf & " ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=TestForm"
TestForm.CodeModule.InsertLines N + 1, MacroString
N = TestForm.CodeModule.CreateEventProc("Click", "AddEventProcButton")
TestForm.CodeModule.InsertLines N + 1, vbCrLf & " AddTestButton"
UserForms.Add(TestForm.Name).Show
End Sub ' DoDataPoints
Sub AddTestButton()
Dim Ctrl As Control
Dim LineCount
Dim N As Long
Dim MacroString As String
Set TestForm = ThisWorkbook.VBProject.VBComponents("UserForm1")
Load UserForm1
MsgBox "Before 'Set', form name = """ & TestForm.Name & """"
MsgBox "After 'Set', before 'With'"
Set Ctrl = UserForms(0).Controls.Add("Forms.CommandButton.1", "TestEventProcButton", True)
With Ctrl
.Caption = "Test Event Proc"
.Height = 24
.Width = 66
.Left = 126
.Top = 18
End With
MacroString = _
"Sub TestEventProcButton_Click()" & vbCrLf & _
" MsgBox ""This routine was added by code""" & vbCrLf & _
"End Sub"
With TestForm.CodeModule
N = .CountOfLines + 1
.InsertLines N, MacroString
End With
End Sub
Sincerely,
Leith Ross
Bookmarks