Consulting

Results 1 to 3 of 3

Thread: For loop to fill textfields

  1. #1
    VBAX Newbie
    Joined
    Jul 2011
    Posts
    3
    Location

    For loop to fill textfields

    Hi,

    I have two userforms, let's say UserForm1 and UserForms2.

    When pressing a button on UserForm2, 12 txtFields on UserForm1 should be filled.

    It works if I would create 12 lines like:
    [VBA]
    UserForm1.txtField1.Value = Range1.Offset(0, 20)
    UserForm1.txtField2.Value = Range1.Offset(0, 21)
    etc.
    [/VBA]

    But I would like to create this via a for loop, I came up with the thing below but it does not work.

    [VBA]
    Dim k As Long
    For k = 1 To 12
    UserForm1.txtField & k & .Value = Range1.Offset(0, k + 19)
    Next k
    [/VBA]

    Please help me. Thanks in advance!
    Last edited by bvs123; 08-06-2011 at 04:28 AM.

  2. #2
    Knowledge Base Approver VBAX Guru GTO's Avatar
    Joined
    Sep 2008
    Posts
    3,368
    Location
    Hi there :-)

    Regardless of where the vals are coming from, the problem is in referencing the control (in this case, textboxes) that we are wanting to access. I may not get this technically correct, but in gist, 'txtField1' is the Object (or CodeName) name. Think of it this way - if your changed the CodeName of "Sheet1" to "shtSheet1", this would not work:

    "shtSheet" & 1 & .Value = "23 skidoo!"

    Fortunately, the userform has a Controls Property, so we can use a string thusly:

    [VBA]Private Sub CommandButton1_Click()
    Dim i As Long

    For i = 1 To 12
    Me.Controls("TextBox" & i).Value = i
    Next
    End Sub[/VBA]

    Hoep that helps,

    Mark

  3. #3
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    Another technique, if you are using descriptive control names, is to loop through an array of controls

    Dim oneControl As Variant
    
    For each oneControl in Array(txtName, txtPhone, txtAddress, txtCity)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •