View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Bob Phillips Bob Phillips is offline
external usenet poster
 
Posts: 10,593
Default Add code on the fly to existing userforms

Here is an example

Sub MakeForm()
Dim TempForm As Object
Dim FormName As String
Dim NewButton As Msforms.CommandButton
Dim TextLocation As Long
'
' Create the UserForm
Set TempForm = ThisWorkbook.VBProject. _
VBComponents.Add(3) 'vbext_ct_MSForm
FormName = TempForm.Name
With TempForm
.Properties("Caption") = "Temporary Form"
.Properties("Width") = 200
.Properties("Height") = 100
End With
'
' Add a CommandButton
Set NewButton = TempForm.Designer.Controls _
.Add("forms.CommandButton.1")
With NewButton
.Caption = "Click Me"
.Left = 60
.Top = 40
End With
'
' Add an event-hander sub for the CommandButton
With TempForm.CodeModule
TextLocation = .CreateEventProc("Click", "CommandButton1")
.InsertLines TextLocation + 1, "MsgBox ""Hello!"""
.InsertLines TextLocation + 2, "Unload Me"
End With
'
' Show the form
VBA.UserForms.Add(FormName).Show
'
' Delete the form
ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=TempForm
End Sub



--
---
HTH

Bob


(there's no email, no snail mail, but somewhere should be gmail in my addy)



"pan65" wrote in message
...
I know I can create a new userform with new controls and new code for the
controls on the fly using VB. I have also added controls to an existing
userform but I am having trouble adding code for the controls. The name
of
my userform is frmGSN and Code is a string of code. I am trying the
following code but it doesn't recognize the .CodeModule

With frmGSN.CodeModule
.InsertLines .CountOfLines + 1, Code
End With

Please help. Thanks