Mega Code Archive

 
Categories / VisualBasic Script / Forms
 

Creating UserForms Programmatically

Sub MakeForm()     Dim TempForm As Object     Dim NewButton As Msforms.CommandButton     Dim Line As Integer     Application.VBE.MainWindow.Visible = False     Set TempForm = ThisWorkbook.VBProject. _       VBComponents.Add(3) 'vbext_ct_MSForm     With TempForm         .Properties("Caption") = "Form"         .Properties("Width") = 200         .Properties("Height") = 100     End With     Set NewButton = TempForm.Designer.Controls _       .Add("forms.CommandButton.1")     With NewButton         .Caption = "Click Me"         .Left = 60         .Top = 40     End With     With TempForm.CodeModule         Line = .CountOfLines         .InsertLines Line + 1, "Sub CommandButton1_Click()"         .InsertLines Line + 2, "  MsgBox ""Hello!"""         .InsertLines Line + 3, "  Unload Me"         .InsertLines Line + 4, "End Sub"     End With     VBA.UserForms.Add(TempForm.name).Show     ThisWorkbook.VBProject.VBComponents.Remove TempForm End Sub