3

Typically when I want to break out of a statement I just set a boolean flag for control flow, but I have a special case with many nested If statements and I'd really like to have a way to break out of several with one simple statement.

In Java you can name a loop and then break to that location; is there anything like that for VBA that can be used from a deeply nested location in If statements? I know VBA has the Exit statement for loops (while, for, etc), so I'm wondering if there is something similar for Ifs.

Ideally I'd like to do something this:

If ...
    *NAMED_IF*
    If ...
         If ...
          :
            *break out of NAMED_IF*
          :
        End If
    End If
    *Now We end up at this control position*
End If
Community
  • 1
  • 1
user1205577
  • 2,388
  • 9
  • 35
  • 47

1 Answers1

6

There isn't an if-statement specific method to break out of nested if-statements, but you could use the GoTo-statement instead:

If ...
    '*NAMED_IF*
    If ...
         If ...

            '*break out of NAMED_IF*'
            GoTo GoToHere

        End If
    End If
End If

'*Now We end up at this control position*
GoToHere:
Netloh
  • 4,338
  • 4
  • 25
  • 38
  • This is great - according to the spec, you can even go to a line number: http://msdn.microsoft.com/en-us/library/vstudio/69whc95c.aspx – user1205577 Nov 07 '13 at 19:11
  • @user1205577 - I cannot tell if you are being facetious :-) – YGA Aug 02 '14 at 00:48
  • 1
    A Word of warning... overused goto statements make your code incredibly difficult to change at a later date by a different developer. If you need to break out of a large block of code, then that block of code should be a function. – Meirion Hughes Oct 01 '14 at 09:41