Assigning label caption with variable in UserForm

T

Tim Golobic

I have columns of labels in a UserForm that I would like to update
using a loop, but have been unable to get the syntax correct with the
loop variable.

There are 24 labels, each labeled Gross_1, Gross_2 .... Gross_24.

A simple statement like

Gross_1 = "1"

updates the caption just fine

But if I try

For MyLoop = 1 to 24
"Gross_" & MyLoop = "1"
Next MyLoop

I receive a syntax error.

I'm trying to avoid assigning the captions with individual statements
since I have 6 more columns exactly like the one above.

Thanks for the help,

Tim
 
J

JE McGimpsey

I have columns of labels in a UserForm that I would like to update
using a loop, but have been unable to get the syntax correct with the
loop variable.

There are 24 labels, each labeled Gross_1, Gross_2 .... Gross_24.

A simple statement like

Gross_1 = "1"

updates the caption just fine

But if I try

For MyLoop = 1 to 24
"Gross_" & MyLoop = "1"
Next MyLoop

I receive a syntax error.

I'm trying to avoid assigning the captions with individual statements
since I have 6 more columns exactly like the one above.

The VBA compiler can't tell you're trying to reference a control when
you use "Gross_" & MyLoop, since it interprets that as trying to
concatenate a string and an integer.

However, you can loop through the labels by specifying items within the
Controls collection:

For i = 1 To 24
UserForm1.Controls("Gross_" & i).Caption = CStr(i)
Next i

Or, if the routine is inside the Userform's code:

For i = 1 To 24
Me.Controls("Gross_" & i).Caption = CStr(i)
Next i
 
Top