Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use string in VBA syntax

Status
Not open for further replies.

WelshTeckie

IS-IT--Management
Aug 9, 2007
37
GB
Hi,

I was wondering is there a way to use a string as part of a command in VBA.

What i'm trying to do is, I have many labels with the same name like Label1, Label2, Label3, etc

and I want to use a for loop to go through each label and do the same thing to all of them, somthing ike this..

For X = 1 to 30
DoCmd = "Label" & X & ".color = red"
Next X

Is there such a thing to be had???
 
Bore da,

try this mate...

Code:
dim ctrl as control
dim x as integer

for x=1 to 30
   set ctrl=me!Label &  Cstr(X)
   ctrl.color=red
next x

JB
 
I do not think the above code will work. No color property that I am aware of. The name syntax will not work. This does.

Dim x As Integer
For x = 1 To 3
Me.Controls("Label" & x).BackColor = vbRed
Next x
 
My bad above, the code shoud be

Code:
Dim ctrl As Control
Dim frmm As Form
Set frm = Me

Dim x As Integer

For x = 1 To 2
   Set ctrl = frm("Label" & CStr(x))
   ctrl.Caption = "red"
Next x

I've set the caption cos there isn't a color property! But it does the job for you, JB
 
How are ya WelshTeckie . . .

With the following method you [blue]Tag[/blue] the labels of interest! (no string required!)
[ol][li]In the [blue]Tag[/blue] property of [blue]each label of interest[/blue], enter a question mark [blue]?[/blue] [red](no quotations please!)[/red][/li]
[li]In the code module of the form, copy/paste the following routine:
Code:
[blue]Public Sub lblColor()
   Dim ctl As Control
   
   For Each ctl In Me.Controls
      If ctl.Tag = "?" Then
         ctl.BackColor = vbRed
      End If
   Next
   
   Set ctl = Nothing

End Sub[/blue]
[/li][/ol]
Now ... you gave no Idea how you intend to [blue]activate/use[/blue] the code, so for testing purposes I'm suggesting the forms [blue]Load[/blue] event with the following:
Code:
[blue]   Call lblColor[/blue]
[blue]Your Thoughts? . . .[/blue]

Calvin.gif
See Ya! . . . . . .

Be sure to see thread181-473997 [blue]Worthy Reading![/blue] [thumbsup2]
Also faq181-2886 [blue]Worthy Reading![/blue] [thumbsup2]
 
Super!

Thanks Guys, thanks for the quick posting.

Got it working, its saved me a lot of repetative code!

Dioch yn fawr!!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top