Creating UserForms Programmatically : Form « Forms « VBA / Excel / Access / Word






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

 








Related examples in the same category

1.Change caption
2.Display form in Modal mode
3.Close a form
4.To remove the Userform from the computer's memory, you must use the Unload statement; otherwise, the Userform is only hidden.
5.Adding Controls to a UserForm at Design Time
6.Output form to html file
7.Using the Show Method to Display a Form
8.Loading a Form into Memory Prior to Displaying It
9.Cancels a cancelable event (an event that has a Cancel parameter).
10.Open a form, format the fonts and close it
11.Format fonts
12.Form count