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!

Creating a UserForm Programmatically 3

Status
Not open for further replies.

jmrdaddy

Technical User
Jun 10, 2002
31
0
0
US
A UserForm can be created using code such as that below.
Code:
Sub Add_Form2()

    ' Declare a variable to hold the UserForm.
    Dim mynewform As Object
    
    ' Create a new UserForm. You can now use this new VBComponent object
    ' to manipulate the User Form.
    Set mynewform = _
        Application.VBE.ActiveVBProject.VBComponents.Add(vbext_ct_MSForm)
    
    With mynewform
        .Properties("Height") = 246
        .Properties("Width") = 616
        .Name = "HelloWord"
        .Properties("Caption") = "This is a test"
    End With
    
End Sub
However, if an attempt is made to run this code a second time an error will be encountered:
Run-time error '75':
"Could not find the specified object."
The code hangs on the .Name = "HelloWord" line. Is there a means by which one can clear the object from memory or whatever so that this error is not encountered? I've tried to delete the forms, tried to unload the forms but nothing seems to work. It appears that it’s the naming of the form that's the problem. I could leave it as "UserForm1" but would like to know how this works anyway.
 
Seems that VBA keeps deleted userforms last custom names and prevents using them again. It is also not possible to rename userform manually using such name. The exception is default UserForm1.. convention by VBA, after deleting a form, a new one can have the same name.
The list frees after saving the file, the code runs again without error.
BTW, you can dim myNewForm as vbComponent.

combo
 
Fabulous! I put the code line below before creating the UserForm. So even if the name has been used before and it's been deleted I don’t get an error! Thanks, you're a champ!
Code:
ActiveWorkbook.Save
 
Thanks all 4 stars,
actually VBA reserves ALL last names of deleted userforms, they can't be used by the user until saving the document. It works in VB...

combo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top