Search code examples
vbafor-loopsyntaxsemantics

VBA: Why do people include the variable's name in a "Next" statement?


I have always written my For-loops like this:

For foo = 1 to 10
    ' do something
Next

However, when I read code snippets online, people always do this:

For foo = 1 to 10
    ' do something
Next foo

I have not noticed any difference between the two, and I can't find any documentation on next statement is more desirable. What is the difference between those two (if any)?


Solution

  • The counter after the Next statement is optional. It used to be required in BASIC-derived languages, but this is no longer the case in VBA.

    You can check the VBA reference:

    If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

    The reason people still add the counter it to increase readability.