Elias
Elias

Reputation: 743

EXCEL VBA: Suspended 'For Loops'

General Question...

What dangers exist if I suspend/exit/interrupt a 'For' loop in my VBA Code (Excel based)?

Here is my code:

For i = 1 to Sheets.Count

    'check stuff
    'do stuff

    if MsgBox("blah blah", vbyesnocancel, "blah") = vbyes then
       'do stuff
        GoTo loopescape
    End if

Next

loopescape:

'rest of code

Basically, I have my code constructed in a way that exits a for loops prematurely (based on a user's input). I am just wondering if this will leave my program susceptible to crashes (or other dangers).

So, do you think interrupting/suspending/exiting a 'for' loop could be problematic?

Thanks,

Elias

Upvotes: 1

Views: 175

Answers (1)

Boann
Boann

Reputation: 50041

That's fine. It's okay to use GoTo to exit a loop. It's not okay to use GoTo to jump in to a 'For' loop though. (Jumping in, depending on the loop variable data type, seems to produce either a run-time error saying the 'For' loop is not initialized, or to silently fail to loop around.)

But you don't need to use GoTo to exit. This is exactly what the Exit For statement is for:

If MsgBox("blah blah", vbYesNoCancel, "blah") = vbYes Then
   'do stuff
    Exit For
End If

Upvotes: 6

Related Questions