View Full Version : how to use a variable to access an object


CALV
12-24-2002, 08:19 AM
Hi all,

Probably simple question, but Im stuck!

I have a subform on a main form wich is basically a list of parts taken from table "parts", there are 15 text boxes called "parts1","parts2", etc with link to the data in the table.

I want to set a for..next to examine these, if they are blank, then I would like to make the relevent text box invisible. If I put "parts1.visible=false" then no problem of course, BUT i want to use a variable instead of typing "part1","part2" etc

i.e.
for x = 1 to 15
tmp = "parts" & x
if tmp.value = null then tmp.visible=false
next x

now the above doesnt work as x is a value rather than a text box, if that makes sense??

TIA

CALV

BukHix
12-24-2002, 08:58 AM
I think this will do it for you.

Dim ctl As Control

For Each ctl In Screen.ActiveForm.Controls
If TypeOf ctl Is TextBox Then
If IsNull(ctl) Then
With ctl
.Visible = False
End With
End If
End If
Next ctl

BukHix
12-24-2002, 09:01 AM
By the way if you need to reverse it on the fly you can do it with this:

Dim ctl As Control

For Each ctl In Screen.ActiveForm.Controls
If TypeOf ctl Is TextBox Then
If ctl.Visible = False Then
With ctl
.Visible = True
End With
End If
End If
Next ctl

CALV
12-24-2002, 09:31 AM
worked fine, thanks a lot!!

out of interest though, how would you address a control using a variable? i.e.

x="parts1"
x.value="hello"

rather than

parts1.value="hello"

CALV

BukHix
12-24-2002, 10:05 AM
I could be wrong but I think you would have to put your controls in an array. I don't have time to figure it out right now but it will be something similar to this. Hopefully some one will come in and give you a better example.

Dim myArray(3)
Dim I As Integer
Dim strString As String
Dim strMessage As String

myArray(0) = "String 1"
myArray(1) = "String 2"
myArray(2) = "String 3"

For I = 0 To 2
strMessage = strMessage & myArray(I) & vbCrLf
Next

MsgBox (strMessage)

Except that you would want to loop through controls instead of the strings I put in the code.

CALV
12-24-2002, 11:03 AM
Thanks, woprks fine with a message box, just wont allow me to access a text box or other control in the same way :( this is really bugging me now lol

Peter Rallings
12-24-2002, 03:05 PM
Dim x As Control
Set x = Me!Salutation
If IsNull(x) Then
x.Visible = False
Else: x.Visible = True
End If