Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Programmatically add code to UserForm 1

Status
Not open for further replies.

patriciaxxx

Programmer
Jan 30, 2012
277
0
0
GB
I have an Access module with the following sub which creates a UserForm (msform not an access form).

How do you add code to the form?

My sample code below both compiles and creates the UserForm complete with the close button but it doesn’t seem to add the code for that button.

Code:
[COLOR=#204A87]Public Sub MyForm()
Dim MyForm As Object
Dim MyNewForm As VBComponent
Dim myItem As Object
Dim x As Integer

Set MyNewForm = Application.VBE.ActiveVBProject.VBComponents.Add(vbext_ct_MSForm)
VBA.UserForms.Add MyNewForm.Name
For Each myItem In UserForms
    If myItem.Name = MyNewForm.Name Then
        Set MyForm = myItem
        Exit For
    End If
Next

MyForm.Width = 240
MyForm.Height = 180
MyForm.Caption = "MyForm"

MyForm.Controls.Clear
MyForm.Controls.Add "Forms.CommandButton.1", "cmdClose"

With MyForm
    .cmdClose.Caption = "Close"
    .cmdClose.Left = 10
    .cmdClose.Top = 10
End With

[COLOR=#4E9A06]'This is the bit which should add the code but doesn’t seem to.[/color]
With MyNewForm.CodeModule
    x = .CountOfLines
    .InsertLines x + 1, "Sub CommandButton1_Click()"
    .InsertLines x + 2, "    Unload Me"
    .InsertLines x + 3, "End Sub"
End With

MyForm.Show
End Sub
[/color]

Does anyone know what I am doing wrong.
 
Code:
[blue]Public Sub MyForm()
    Dim MyNewForm As VBComponent
    Dim myItem As Object
    Dim x As Integer
    
    Set MyNewForm = Application.VBE.ActiveVBProject.VBComponents.Add(vbext_ct_MSForm)
    
    With MyNewForm
        .Properties("Width") = 240
        .Properties("Height") = 180
        .Properties("Caption") = "MyForm"
        .Designer.Controls.Clear
        Set myItem = .Designer.Controls.Add("Forms.CommandButton.1", "cmdClose")
    End With
    
    With myItem
        .Caption = "Close"
        .Left = 10
        .Top = 10
    End With
    
    With MyNewForm.CodeModule
        x = .CountOfLines
        .InsertLines x + 1, "Sub cmdClose_Click()"
        .InsertLines x + 2, "    Unload Me"
        .InsertLines x + 3, "End Sub"
    End With
    
    UserForms.Add(MyNewForm.Name).Show
End Sub[/blue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top