问题
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)?
回答1:
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.
回答2:
It's for when you have multiple for
loops.
For example,
For i to j
For k to l
next k
next i
Otherwise, the next
is ambiguous. It's not absolutely necessary, as the loop will still work without it, but it's just good practice to have it marked for the sake of anyone else reading your code.
来源:https://stackoverflow.com/questions/21993482/vba-why-do-people-include-the-variables-name-in-a-next-statement