jiri jansa
jiri jansa

Reputation: 159

returning back to loop after using GoTo

I have tried several methods but didn´t manage to succeed. My problem is - running loop1, if some condition is fulfilled, run loop2 until some condition is fulfilled, return back to loop1.

sub program()
Dim i As Integer
Dim q As Integer

For i=1 to 350
If Range("A"&i).value=1 And Range("D"&i).Value<15 Then Goto 1
Next i

1:q=0
  Do While List1.Range("A"&i+q).Value<>""
  Range("E"&i+q)="K"
  q=q+1
  Loop

End Sub

I haven't found the way how to return after executing "1 loop" back to "For Next Loop" and continue for next i. Maybe it is not possible and I have to include somehow code inside the first loop ?! thank you

Upvotes: 0

Views: 16024

Answers (3)

FCastro
FCastro

Reputation: 631

Usage of GoTo is discouraged even by MSDN (you should use it only for error treatment paired with Resume), but since you asked, this is the approach:

Sub program()
    Dim i As Integer
    Dim q As Integer

    For i=1 to 350
        If ((Range("A"&i).value=1) And (Range("D"&i).Value<15)) Then Goto OtherLoop
FirstLoop:
    Next i

Exit Sub

OtherLoop:
   q=0
   Do While List1.Range("A"&i+q).Value<>""
       Range("E"&i+q)="K"
       q=q+1
   Loop
   Goto FirstLoop

End Sub

You need the Exit statement to keep your code from entering "OtherLoop" when it finishes "FirstLoop", and also need to tell it to go back to where you previously were. Again, avoid using this stuff. Loops within loops (indent to organize, please) and secondary procedure calls (calling another sub or function) are far more recommended.

Upvotes: 0

James Youngman
James Youngman

Reputation: 3733

I don't actually know VBA (I last used VB in about 1996) but this should be more or less right:

sub program()
Dim i As Integer
Dim q As Integer

i = 1
Do while i <= 350
  If Range("A"&i).value=1 And Range("D"&i).Value<15 Then
    Do While i <= 350 And List1.Range("A"&i).Value<>""
      Range("E"&i)="K"
      i=i+1
    Loop
  Else
      i=i+1
  End If
Loop
end do
End Sub

Upvotes: 1

user420442
user420442

Reputation:

Make the code at 1 into a function and call that instead of using goto. When the function exits, your first loop will continue executing from where it left off.

Upvotes: 3

Related Questions