Reducing code, dynamic names
Another simple question that i'm not familiar with in vb :sick:
In say actionsctipt etc i can reduce a lot of code by creating dynamic variable names etc
How to i transform somthing like this:
Code:
PictureBox1.Visible = False
PictureBox2.Visible = False
PictureBox3.Visible = False
Into something like this, (which i know is very wrong!):
Code:
Dim i As Integer
For i = 1 To 3
"PictureBox"&i = False
Next
Any help is much appreciated
Re: Reducing code, dynamic names
See if this helps
Code:
Private Sub Command1_Click()
Dim i As Integer
Dim pic As PictureBox
For i = 1 To 3
Set pic = Controls("Picture" & i)
pic.Visible = Not pic.Visible
Next i
End Sub
Re: Reducing code, dynamic names
What if its just a variable that i want to do?
like LED1, LED2, LED3
Re: Reducing code, dynamic names
Create a control array:- Create a picturebox.
- Change it's Name to PB.
- Change it's Index to 0.
- Copy PB to clipboard.
- Paste. The new control gets Index 1.
- Paste. The new control gets Index 2.
You now have three pictureboxes, all have the name PB. You can access the first one with PB(0), second with PB(1) and third with PB(2).
Re: Reducing code, dynamic names
Quote:
What if its just a variable that i want to do?
try using an array
vb Code:
dim led() as string
redim led(3) ' 0 to 3 = 4 elements
for i = 0 to ubound(led)
led(i) = "element " & I
next
Re: Reducing code, dynamic names
Quote:
Originally Posted by
MarkT
See if this helps
Code:
Private Sub Command1_Click()
Dim i As Integer
Dim pic As PictureBox
For i = 1 To 3
Set pic = Controls("Picture" & i)
pic.Visible = Not pic.Visible
Next i
End Sub
You don't need the variable; controls can be accessed by name directly.
Code:
Private Sub Command1_Click()
Dim i As Integer
For i = 1 To 3
Me("Picture" & i).Visible = False
Next
End Sub
EDIT: Though in looking back at this I'm guessing you already know this and only used a variable because you're referencing the control twice. (Visible = Not Visible) I suppose if you wanted to keep the code clean and save a variable you could use a With...End With block.