Home » excel » excel – VBA increment the "#" in TextBox#.value

excel – VBA increment the "#" in TextBox#.value

Posted by: admin May 14, 2020 Leave a comment


i need help in VBA coding:
i have nearly 250 TextBox in an user form (is a “matrix” of values), and when user finish fill the boxes, I want to write them in the excel sheet.
I could write all 250 lines as

WorkSheets(mysheet).Cells(x,y).Value = TextBox#.Value

but this would be very long. I wanna know if there is a way to make something like a while, and increment the # of the textbox.
Thanks, and sorry for my english.

How to&Answers:

One option is to use code as follows which will give you each textbox. Another option is if the boxes are named with a trailing number (i.e. Txt1, Txt2, etc.), then you could use other code (i.e. Me.Controls(“TextBox” & i).Value

Dim cCTL As Control
Dim iCTR As Integer
iCTR = 0
For Each cCTL In Me.Controls
    If TypeName(cCTL ) = "TextBox" Then
        iCTR = iCTR + 1
        WorkSheets(mysheet).Cells(iCTR,y).Value = cCTL.Value
    End If
 Next cCTL 

Option Two (Since all controls are numbered: Just set the For loop to the proper count of controls, and change the ‘mysheet’ reference to be the column & row you want.

Dim i   As Integer
For i = 1 to 250
    WorkSheets(mysheet).Cells(i+2,y).Value = Me.Controls("ctr" & i).value
Next i