Search code examples
vbaexceltextbox

Transfer multiple textbox values to array


I have a userform with 13 textboxes from which I'm trying to transfer the values of the last 10 (ie #4-#13) into an array. My thinking was to cycle through all controls on the form and use a simple counter to skip the first 3 textboxes, then set my array elements to the rest of the textbox values in turn.

For Each Ctrl In Me.Controls
    If TypeName(Ctrl) = "TextBox" Then
        i = i + 1
        If i > 3 Then
            PO(i - 3) = Ctrl.Value
        End If
    End If
Next Ctrl

The concept itself works; however, the cycle starts with textbox #3 instead of #1, and I end up getting the following values in my array - (#6-#13, #1, #2). So, the first textbox control it is finding is #3, then going through to #13 and coming back to #1 and #2.

The boxes are named (and tab indexed) in the logical order to fit what I'm trying to do, but obviously there is something about this procedure that I don't quite get - or VBA gets it in a different way than I do.

Is it possible that the For Each Ctrl statement goes through controls in the order in which they were originally created, rather than the order of the tabindex or name? If so, how could I find the original order of creation?


Solution

  • You can do it like this, using the consistent structure of the controls' names.

    For i = 4 To 13
        PO(i - 3) = Me.Controls("Textbox" & i).Value
    Next i