The basic structure of the FOR Next statement is:
Copy Code code as follows:
For counter = start to end [step step]
[Statements]
[Exit for]
[Statements]
Next
When the for Next Loop starts, Visual Basic scripting Edition (VBScript) assigns the start assignment to counter. Compares counter with end before the statement block in the loop is run. If the counter has exceeded the end value, the for loop terminates and the control process jumps to the next statement. Otherwise, the statement block in the loop is run.
Each time VBScript encounters Next, it adds counter to the step and returns it to the for. It compares the values of the counter and end again, and continues to run the block of statements in the loop or terminate the loop based on the result. This process continues until the counter is exceeded or an Exit for statement is encountered.
The above is common sense, simple mention to gather words, below is a you may ignore the details:
The loop control variable start end and step are evaluated only once before the start of the loop, and if the statement block in the loop changes the value of the last or the move, the change does not affect the loop's operation.
Write a simple VBS script to verify:
Copy Code code as follows:
' Author:demon
' Date:2012-1-19
n = 10
s = 1
For i = 1 to n step s
WScript.Echo I
n = 5
s = 2
Next
WScript.Echo N, S
We changed the value of N and S in the loop, but the loop still went 10 times, sequentially outputting 1 to 10, which means that a copy of the loop control variable n and S is kept inside the for Next Loop, and the internal variable is used to control the flow of the loop.
Understanding this detail can help us write efficient and concise code:
Copy Code code as follows:
' Author:demon
' Date:2012-1-19
s = "Http://jb51.net"
For i = 1 to Len (s)
WScript.Echo Mid (S, I, 1)
Next
' This C Style is no more efficient than the above
' Do not need to do this in the for Next loop of the VBS
L = Len (s)
For i = 1 to L
WScript.Echo Mid (S, I, 1)
Next
It is worth noting that changing the counter in the loop is permissible, but you should avoid doing so, which will only make your scripts difficult to read and debug.
Copy Code code as follows:
' Author:demon
' Date:2012-1-19
For i = 1 to 10
WScript.Echo I
i = i + 2 ' do not advocate doing this
Next
Reference Link: http://msdn.microsoft.com/en-us/library/sa3hh43e%28v=vs.85%29.aspx
Original: http://demon.tw/programming/vbs-for-next.html