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

泪湿孤枕 提交于 2020-01-03 13:35:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!