short circuit for next; continue?

C

cate

Is there a way to do this in vba? (I can do this with structure but I
want to know if there is a perl/C# analog to (continue")

for x = 2 to y

answer = sub_testing()
if answer = 1
continue ' skip the reset of loop code and go back and get the
next value. No point in going on
end if

do more stuff
do more stuff

next

thank you.
 
J

JLGWhiz

Not sure I understand what you mean, but I think maybe Exit For is what you
are looking for.
For i = 1 To 10
If condition is met then
Exit For
End If
'Do stuff
Next
The Exit for will take you out of the loop to the next line of code.
 
P

Peter T

There's not a direct equivalent to 'continue' in VB but two ways to achieve
same with your example

for x = 2 to y

answer = sub_testing()
if answer <> 1 then

do more stuff
do more stuff

end if

next


for x = 2 to y

answer = sub_testing()
if answer = 1
goto continue
end if

do more stuff
do more stuff

continue:
next

("continue" here is just a label named whatever you want)

I should add purists don't like use of Goto and will give all sorts of
(good) reasons not to use it. That said if used sparingly it can be useful.

Regards,
Peter T
 
C

cate

Not sure I understand what you mean, but I think maybe Exit For is what you
are looking for.
For i = 1 To 10
  If condition is met then
     Exit For
  End If
  'Do stuff
Next
The Exit for will take you out of the loop to the next line of code.

With if's it would look like this

For i = 1 To 10
If condition is met then
do stuff
end if
Next

verses (with continue) The same result

For i = 1 To 10
If condition is NOT met then
continue
end if
do stuff
Next
 
C

cate

There's not a direct equivalent to 'continue' in VB but two ways to achieve
same with your example

for x = 2 to y

  answer = sub_testing()
  if answer <> 1 then

  do more stuff
  do more stuff

  end if

next

for x = 2 to y

  answer = sub_testing()
  if answer = 1
       goto continue
  end if

  do more stuff
  do more stuff

continue:
next

("continue" here is just a label named whatever you want)

I should add purists don't like use of Goto and will give all sorts of
(good) reasons not to use it. That said if used sparingly it can be useful.

Regards,
Peter T

Thank you.
 
D

Don Guillett

If I understand

y=12
for i = 2 to y
if lcase(cells(i,"b"))="yes" then
msgbox cells(i,"c")
exit for
else
msgbox "go on"
end if
next i
 
R

Rick Rothstein

Just change your If..Then test to the negative and include you "do more
stuff" inside the If..Then block, that way, the x=1 condition will naturally
"fall through"...

For x = 2 To y
answer = sub_testing()
If answer <> 1 Then
do more stuff
do more stuff
End If
Next
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top