asked on
Change the name of a VBA form programmically.
I'm using VBA to create a UserForm with controls on it, That all works, however each UserForm is created with the name UserForm1, UserForm2, etc. I'm unable to programmically change the UserFrom name using:
Application.ActiveDocument.VBProject.VBComponents("UserForm1").Name = "ufMainColorForm"
I get the following error "Run-time error 75: Path/File access error"
The "Name" property seems to be read-only, i.e., I can list all the form names, just can't change any of them except manually through the IDE.
Above example is from MS Word, but Excel shows the same problem.
Any suggestions would be much appreciated.
In Excel, you will get a runtime error saying that access to the VBProject isn't trusted. The cure is to check the box to Trust access to the VBA project object model in the File...Options...Trust Center...Trust Center Settings...Macro Settings ribbon item. Word has the same checkbox.
Having done that, you may then use code in Excel like shown below to rename UserForm1:
Sub RenameUserForm()
Application.ActiveWorkbook.VBProject.VBComponents("UserForm1").Name = "ufMainColorForm"
End Sub
I have created a small example for you adding a UserForm with a button and combobox adapted form one of my projects.
MakeUserForm.xlsm
You won't be able to rename the form while it is loaded and would get an access error.
ASKER
ASKER
Thanks
ASKER
That wasn't my issue. I'm able to create a form and populate with controls without issue, programmatically. The only issue was programmatically changing the form name. Initially, the form name is UserForm1. I want to change the name to something more descriptive as I have multiple forms.
Yes, Chip's site is terrific.
Thanks
ASKER
Thanks, Denis
ASKER
ASKER
Thanks Martin, but using the tag property doesn't solve my issue. To add controls to the form, I have reference the form name.Try something like this:
Dim frm As Object
For Each frm In VBA.UserForms
If frm.Tag = "Whatever" Then
Msgbox frm.name
End If
Next
ASKER
Thanks Martin, that is a workaround. I was hoping that I could change the form name itself. Otherwise, what shows up in the Project Explorer is UserForm1, UserForm2, UserForm3....Since I'm unable to find a way to programmatically change the form name, I'll just do it manually for this application.
ASKER
Again, thanks for everyone's help.
Denis
Open in new window