repeat same if then statement for multiple variables

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

under one subroutine, i repeat the same if then statement on several variables.

basically i have the following structure:

if a1 < dob then (do something to a1)
if a2 < dob then (do something to a2)
....
if z4 < dob then (do something to z4)

what i would really like do is to condense this. these aren't the only
variables on the form, so i'm thinking that doing something like this won't
work:

Dim ctrl as Control
For each ctrl in Me.Controls
If ctrl < dob then (do something to ctrl)
Next ctrl

so i tried something like this:

Dim ctrl as Control
Dim i as Integer
For i = 1 to Controls.count
ctrl = Control(i). ???
Select Case ctrl
Case "a1", "a2", ... "z4"
If ctrl < dob then (do something to ctrl)
End Select
Next i

but clearly i'm not sure how to finish this or if i'm even on the right
track. if it sounds nonsensical, it's because i had a piece of script in
another language and i'm trying to translate it to vb (and my vb knowlege
isn't extensive).

thanks for any help!
 
Hi Jennifer

There are several ways you could do this. Here are a couple:

1. Use an array of control names:

Dim aControls as variant, sControl as string, ctrl as Control
aControls = Array("a1", "a2", ... "z4")
For each sControl in aControls
Set ctrl = Me(sControl)
If ctrl < dob then
' do something with ctrl
End If
Next sControl

2. Use the Tag property - for each of the controls in question, set it to
some testable value, say "X"

Dim ctrl as Control
For each ctrl in Me.Controls
If ctrl.tag = "X" Then
If ctrl < dob then
' do something with ctrl
End If
End If
Next sControl
 
Actually your pseudocode is dead on - the only thing you might want to do is
to put something in the tag property of each of these controls and then use
the tag to determine whether to use this control in the loop. This way you
can tag your controls without changing the code. For example you might put
"CompareDOB" into the tag property then your code would look like this:

Dim ctrl as Control
For each ctrl in Me.Controls
if ctrl.tag="CompareDOB" then
If ctrl < dob then (do something to ctrl)
'your code here - just keep referring to ctrl
endif
endif
Next ctrl

If you don't want to use the tag property then you will have to either
compare the control name to a list of names or use a common prefix as for
all control names.
 
1. was exactly what i was looking for. i'm actually not using access, but
another program that uses vb in a very similar way to access. unfortunately,
i don't have the tag property in that program.

thank you much.
jen
 
Back
Top