Looping Statements in VBScript - More On Loops
(Page 4 of 4 )
There is one final looping method that provides a conditional loop. The While…Wend provides a shorthand for the Do While…Loop syntax. However, since it is less flexible its use has been depreciated. Here’s an example of our first conditional loop:
x = 1
While x <> 5
WScript.Echo x
x = x + 1
Wend
A While…Wend loop will only continue to execute as long as its conditional statement evaluates to True.
From time to time you may wish to end the execution of a loop before it completes. This can be done using the Exit statement. Typically this will be used in conjunction with an IF statement to exit execution when an outside condition is met.
For x = 1 To 10
WScript.Echo x
If x = 5 Then
Exit For
End If
Next
arrWords = Array("one", "two", "three", "four", "five", _
"six", "seven", "eight", "nine", "ten")
For Each strWord In arrWords
WScript.Echo strWord
If strWord = "five" Then
Exit For
End If
Next
x = 1
Do While x <> 10
WScript.Echo x
If x = 5 Then
Exit Do
End If
x = x + 1
Loop
Each of the loops above has been modified so that it exits before execution completes. The output provided by these loops is the same as the previous examples even though the conditions have been changed to provide a much wider range of numbers.
1
2
3
4
5
one
two
three
four
five
1
2
3
4
5
Learning to use loops effectively can greatly increase the flexibility and power of your scripts. Be sure to take the time to try nesting and combining your loops. This can open up whole new avenues of scripting techniques for you to use. Until next time, keep coding!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |