Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an if statement inside a for loop in VBA?

Tags:

for-loop

vba

For a = 1 to 10
    if a = dumm then next a 'this statement should avoid running the subsequent codes if the if statement is true (similar to continue in c++
    end if
    'statements that need to run when the if statement is not true

next a 

Why does this code not work?? It throws compile error: Next without for

like image 644
pnkjmndhl Avatar asked Oct 16 '25 05:10

pnkjmndhl


1 Answers

Why does this code not work?? It throws compile error: Next without for

Because you have a next without a corresponding For. For/Next and For Each/Next must be paired, you can't open a For loop without a Next and you can't use Next without `For.

Simply:

if a = dumm then a = a + 1

This increments your a value within the loop. I'm unclear as to why you think this isn't applicable, because whether you increment a and then run the code, or skip to the next a (which is functionally equivalent to incrementing it via +1), the result should be same

Or, you could add a label and a GoTo statement:

For a = 1 to 10
    if a = dumm then 
        GoTo MyLabel 
    end if
    'statements that need to run when the if statement is not true

MyLabel:
next a 

Or, and my preference, just use proper boolean expressions:

For a = 1 to 10
    if not a = dumm Then
        'statements that need to run when the if statement is not true
    end if
Next

If you don't want to continue the loop at all, then either add an Exit statement,

For a = 1 to 10
    if a = dumm Then Exit For
    'statements that need to run when the if statement is not true

Next

or use a Do/While loop with proper escape conditions:

a = 1
Do 
    'statements go here...    
    a = a + 1
Loop While a <= 10 and Not a = dumm 
like image 113
David Zemens Avatar answered Oct 19 '25 13:10

David Zemens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!