Looping Question

  • Thread starter Thread starter trekgoes2malaysia
  • Start date Start date
T

trekgoes2malaysia

I want to use an if....end if statement in VBA that repeats over 20
times. The problem is that each iteration of the loop involves a
different field in my table (20 different fields) so the coventional
way of looping doesn't work. How can I do this without having to
repeat the if....end if statement 20 times in code. below is my code:

If Me.Txtm1 >= getdistance Then
Me.Txtm1.Visible = False
Me.t1.Visible = False
Me.tt1.Visible = False
Me.S1.Visible = False
End If

If Me.Txtm2 >= getdistance Then
Me.Txtm2.Visible = False
Me.t2.Visible = False
Me.tt2.Visible = False
Me.S2.Visible = False
End If

etc up to 20 times.

Patrick
 
Try:

Dim intLoop As Integer

For intLoop = 1 To 20
If Me.Controls("Txtm" & intLoop) >= getdistance Then
Me.Controls("Txtm" & intLoop).Visible = False
Me.Controls("t" & intLoop).Visible = False
Me.Controls("tt" & intLoop).Visible = False
Me.Controls("S" & intLoop).Visible = False
End If
Next intLoop

You can make that even simpler:

Dim intLoop As Integer

For intLoop = 1 To 20
Me.Controls("Txtm" & intLoop).Visible = _
(Me.Controls("Txtm" & intLoop) < getdistance)
Me.Controls("t" & intLoop).Visible = False
(Me.Controls("Txtm" & intLoop) < getdistance)
Me.Controls("tt" & intLoop).Visible = False
(Me.Controls("Txtm" & intLoop) < getdistance)
Me.Controls("S" & intLoop).Visible = False
(Me.Controls("Txtm" & intLoop) < getdistance)
Next intLoop

The second approach ensures that the controls will be visible when the
condition you're checking isn't true, something your code doesn't do.
 
Back
Top