I am trying to sequentially rename the textboxes on my userform. Whatever I try I end up with errors. (Runtime error 382 'Could not set the name property. Can not set property at run time') I have tried adding the code to Userform_Initialize and everywhere else but with no success. Help would be appreciated. This is my code:
Private Sub UserForm_Initialize() Dim Ctrl As Control Dim i As Long Dim cnt As Long cnt = 1 For Each Ctrl In UserForm1.Controls If TypeName(Ctrl) = "TextBox" Then Ctrl.Name = "TextBox" & cnt cnt = cnt + 1 End If Next Ctrl End Sub
Last edited by BillWilts; 10-14-2010 at 08:04 AM.
The error means exactly what it says - you can't do that (why would you want to?)
Note: when posting code on the forum, you must use code tags, please. I have added them for you here as it's your first post, but please use them in future.
The reason behind the question is that I would like (as phase 2 of my current project) to build a multipage form with textboxes that can be added or deleted dynamically. Renaming the textboxes would allow me to simplify the process of populating the textboxes with data and writing the changes back to the spreadsheet. It's much easier to loop through a contiguous range!
If you add the textboxes dynamically, you can name them as you add them. I still can't see a reason for needing to change the names.
Thanks for pointing me in the right direction! I now have some code to create the boxes but am having a mental block regarding referencing them. Obviously they don't exist until the form is visible so 'Userform1.TextBox1.Value = ...' does not work. Can you give me some idea as to how they should be referenced?
This is the code to create them.
Private Sub ShowForm() Dim cCntrl As Control Dim BoxNum, BoxTop As Integer ' Set the value for the background color ColorGrey = RGB(192, 192, 192) ' Position of first box BoxTop = 6 ' Add the boxes for the labels For BoxNum = 1 To 5 Set cCntrl = UserForm1.Controls.Add("Forms.TextBox.1", _ "TextBox" & BoxNum, True) With cCntrl .Width = 150 .Height = 18 .Top = BoxTop .Left = 6 .ZOrder (0) .BackColor = ColorGrey .Locked = False End With With cCntrl.Font .Name = "Arial" .Size = 10 End With ' Increment value for top of next boxes BoxTop = BoxTop + 24 Next UserForm1.Show End Sub
You can use:
in a loop. Typically though you would use a class to control the controls you add at runtime, depending on why you added them and what you are doing with them.Me.Controls("Textbox" & i)
That works fine! Thanks for you help.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks