112

I just moved over to the Visual Basic team here at work.

What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tyronomo
  • 2,047
  • 2
  • 15
  • 22
  • For the other way around, in C#: *[C# loop - break vs. continue](https://stackoverflow.com/questions/6414/c-sharp-loop-break-vs-continue/6417#6417)* – Peter Mortensen Jun 24 '17 at 17:39

3 Answers3

198

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

John
  • 29,788
  • 18
  • 89
  • 130
  • 11
    Also on a related note, "Continue" will allow you to skip to the next iteration in a for loop. – StingyJack Mar 03 '09 at 17:08
  • 6
    @StingyJack Worth noting that `Continue` is only available in VB.Net, not VB6 – MarkJ Sep 19 '11 at 10:47
  • 1
    `Exit While` is not valid in VB7...use convert from `While...Wend` to `Do While...Loop` and an `Exit Do` will then work. – Merk Sep 17 '13 at 20:24
  • @Merk Exit While is documented here - https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement do you have document on when it is not supported? – John Mar 20 '18 at 09:08
  • 1
    @StingyJack In older VB you can use `Goto – dekuShrub Jul 22 '21 at 11:50
  • 2
    @dekuShrub you can use GoTo in .net languages also, but there is usually a better alternative, like making NextDataEntry() into a function – StingyJack Jul 22 '21 at 12:25
  • Ah, maybe I should have mentioned @MarkJ instead of you. I just wanted to provide a way of doing it in older VB :) – dekuShrub Jul 22 '21 at 12:29
  • Yes, I support both! `GoTo` in VB6 can be an OK way to work around the absence of the `Continue` statement. Or creating a function can work well too. – MarkJ Jul 27 '21 at 16:28
  • Wow, this comment conversation has been going on more than 10 years! Can't believe I only just upvoted @StingyJack's comment from 2009 – MarkJ Jul 27 '21 at 16:29
7

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Ayman El Temsahi
  • 2,600
  • 2
  • 17
  • 27
  • Useful answer, but not really in the context of the question as that's what they explicitly said they didn't want to do. – Deanna Apr 16 '13 at 10:40
4

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Eric Haskins
  • 8,505
  • 12
  • 38
  • 47