2

how do you tell vba to go back up to an earlier line in your code. I'd imagine i need to use the GoTo command, but i'm not sure.

Alex Thibault
  • 31
  • 1
  • 1
  • 3
  • 1
    GOTO is usually frowned upon, if you present an example you will likely get an answer that uses a loop construction. – Alex K. Jun 02 '15 at 15:15
  • Why is GoTo frowned upon? – Lance Jun 02 '15 at 15:18
  • 1
    Because it can usually be replaced with loop constructions that offer greater clarity of intent and less possibility of error. Its subjective of course. http://stackoverflow.com/questions/46586/goto-still-considered-harmful – Alex K. Jun 02 '15 at 15:34
  • I agree that you should use a loop when appropriate but if you are simply wanting to skip a block of code if some condition exists then GoTo is a good way to do it. It depends on what you're trying to accomplish. – Lance Jun 02 '15 at 15:55

2 Answers2

4

This should work. Note that this is just an example. You should never use goto to accomplish what is being done here. A while loop would be better for example.

Sub gotoExample()
        Dim a As Integer
        a = 1
line1:
        a = a + 1
        If a < 10 Then
            GoTo line1
        End If
End Sub
burtelli
  • 153
  • 9
1

You can use GOTO like so:

some code
...

if some exit condition goto label

more code that gets skipped
...

label:
exit routine
Lance
  • 3,824
  • 4
  • 21
  • 29