0

I used code provided on Creating form programmatically in the module using vba to create the dynamic form, everything works great for the most part, however, the only way I can close the form is using the red "X" in the corner and I want to be able to close it with a button.

I have tried using the simple Unload UserForm1 and tried to call the UserForm_QueryClose command as well, but nothing seems to work. I have also tried ThisWorkbook.VBProject.VBComponents.Remove ("UserForm1"), but I push the button and nothing happens.

This creates the form:

Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3)

'Create the User Form
With myForm
    .Properties("Width") = 270
    .Properties("Height") = 376
End With

This creates the command button:

'Create CommandButton Create
Set NewButton = myForm.designer.Controls.Add("Forms.commandbutton.1")
With NewButton
    .Name = "cmd1"
    .Caption = "Ok"
    .Accelerator = "M"
    .Top = 100
    .Left = 200
    .Width = 66
    .Height = 20
    .Font.Size = 8
    .Font.Name = "Tahoma"
    .BackStyle = fmBackStyleOpaque
End With

This fills out the code in the form:

'add code for Command Button
myForm.CodeModule.InsertLines 16, "Private Sub cmd1_Click()"
myForm.CodeModule.InsertLines 17, "Unload UserForm1"
myForm.CodeModule.InsertLines 18, "End Sub"

I expect the form to unload once the button is pushed and move on to the next procedure, but nothing happens. I have tested other commands when hitting the button and it seems to work, but I just can't get it unloaded without pushing the red "X".

Gordon
  • 1
  • 1
    Your code is going to unload Userform1 when you should be unloading myForm. – ProfoundlyOblivious Jun 24 '19 at 18:34
  • @ProfoundlyOblivious the name of the form that is generated is Userform1, it is only Dimed as myForm in the module, but when the code is added to the Userform1, it does not recognize myForm, since that is not its actual name. Hopefully that clears some things up. Thanks for the response. – Gordon Jun 25 '19 at 11:42

0 Answers0