user3903709
user3903709

Reputation:

Condetional break inside the For loop and continue execution

How can i break the loop and continue execution from the next line comes after the loop, if condition inside the loop is/are true. i tried labels and GoTo but it will executed all time will not depend on the condition inside the loop. i have the following code :

 Dim i As Integer
 For i = 1 To 50
    If i > 35 Then
    ' break the loop
    End If
 Next

I had tried with GoTo it works properly, some times it execute by default doese not depend on the condition given inside the loop

  If i > 35 Then
    GoTo lbl
  End If 
lbl: ' code comes here

Thank you......

Upvotes: 0

Views: 75

Answers (2)

Suji
Suji

Reputation: 1326

You can use the Exit command for this kind of break ; Exit Sub is used to comes out from a particular Sub, Exit Function will help you to comes out from a function, here you can use Exit For hence your code will be like the following

Dim i As Integer
For i = 1 To 50
If i > 35 Then
Exit For
End If
Next

Upvotes: -1

GSerg
GSerg

Reputation: 78175

If i > 35 Then
    Exit For
End If

However your code with Goto would work too - provided the lbl: is outside the loop.

Upvotes: 4

Related Questions