VBS Tutorial: VBScript basics-Use loop statements

Source: Internet
Author: User

Use loop statements

Loop is used to repeatedly execute a set of statements. Loops can be divided into three types: one type changesFalseExecute the statement repeatedly before.TrueThe statement is executed repeatedly before, and the other type repeats the statement according to the specified number of times.

The following statements can be used in VBScript:

  • Do... Loop: When (or until) the condition isTrueCycle.
  • While... Wend: when the condition isTrueCycle.
  • For... Next: specify the number of cycles and use the counter to run the statement repeatedly.
  • For Each... Next: executes a set of statements repeatedly For Each element in the set or array.

(The preceding statements are described in detail below)

Use Do loop

AvailableDo... LoopThe statement block is run multiple times. When the condition isTrueOr the condition changesTruePreviously, statement blocks were repeatedly executed.

Execute the statement repeatedly when the condition is True.

WhileKeyword used for checkDo... LoopStatement. There are two ways to check the conditions: Check the conditions before entering the loop (the following ChkFirstWhile example); or check the conditions after the loop is run at least once (the following ChkLastWhile example ). During ChkFirstWhile, if the initial value of myNum is set to 9 rather than 20, the statement in the loop body will never be executed. During ChkLastWhile, the statement in the loop body is executed only once, because the condition is alreadyFalse.

 Sub ChkFirstWhile()     Dim counter, myNum     counter = 0     myNum = 20     Do While myNum > 10         myNum = myNum - 1         counter = counter + 1     Loop     MsgBox "Repeated Loop " & counter & " Times." End Sub Sub ChkLastWhile()     Dim counter, myNum     counter = 0     myNum = 9     Do         myNum = myNum - 1         counter = counter + 1     Loop While myNum > 10     MsgBox "Repeated Loop " & counter & " Times." End Sub
Execute the statement repeatedly until the condition changes to True.

UntilKeyword used for checkDo... LoopStatement. There are two ways to check the condition: Check the condition before entering the loop (the following ChkFirstUntil example); or check the condition after the loop is run at least once (the following ChkLastUntil example ). If the condition isFalse.

 Sub ChkFirstUntil()     Dim counter, myNum     counter = 0     myNum = 20     Do Until myNum = 10         myNum = myNum - 1         counter = counter + 1     Loop     MsgBox "Repeated Loop " & counter & " Times." End Sub Sub ChkLastUntil()     Dim counter, myNum     counter = 0     myNum = 1     Do         myNum = myNum + 1         counter = counter + 1     Loop Until myNum = 10     MsgBox "Repeated Loop " & counter & " Times." End Sub
Exit Loop

Exit DoStatement used to exitDo... LoopLoop. Because in some special circumstances, the loop is usually to exit (for example, to avoid an endless loop), you canIf... Then... ElseStatementTrueUse in statement BlockExit DoStatement. If the condition isFalse, And the loop will run as usual.

In the following example, the initial value of myNum will lead to an endless loop.If... Then... ElseStatement checks this condition to prevent endless loops.

 Sub ExitExample()     Dim counter, myNum     counter = 0     myNum = 9     Do Until myNum = 10         myNum = myNum - 1         counter = counter + 1         If myNum < 10 Then Exit Do     Loop     MsgBox "Repeated Loop " & counter & " Times." End Sub
Use While... Wend

While... WendStatements are provided for users who are familiar with their usage. HoweverWhile... WendLack of flexibility, so it is recommended to useDo... LoopStatement.

Use For... Next

For... NextThe statement is used to run the specified number of times in the statement block. Use counter variable in a loop. The value of this variable increases or decreases with each loop.

For example, the following example repeats MyProc 50 times.ForThe statement specifies the counter variable x, its start value, and the end value.NextStatement to add 1 to each counter variable.

 Sub DoMyProc50Times()     Dim x     For x = 1 To 50         MyProc     Next End Sub

KeywordsStepUsed to specify the value of each increase or decrease of counter variables. In the following example, the counter variable j is added with 2 each time. After the loop ends, the total value is the sum of 2, 4, 6, 8, and 10.

 Sub TwosTotal()     Dim j, total     For j = 2 To 10 Step 2         total = total + j     Next     MsgBox "Total is " & total & "." End Sub

To reduce the number of counter variables, you canStepSet it to a negative value. The end value of the counter variable must be smaller than the start value. In the following example, the counter variable myNum is reduced by 2 each time. After the loop ends, the total value is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.

 Sub NewTotal()     Dim myNum, total     For myNum = 16 To 2 Step -2         total = total + myNum     Next     MsgBox "Total is " & total & "." End Sub

ExitThe statement is used to exit before the counter reaches its termination value.For... NextStatement. Because in some special circumstances (for example, when an error occurs ),If... Then... ElseStatementTrueUse in statement BlockExitStatement. If the condition isFalse, And the loop will run as usual.

Use For Each... Next

For Each... NextLoop andFor... NextThe loop is similar.For Each... NextInstead of running a specified number of statements, it repeats a set of statements for each element in the array or object set. This is useful when you do not know the number of elements in the collection.

In the following example,DictionaryThe object content is used to place the text in multiple text boxes:

 <HTML> <HEAD><TITLE>Forms and elements</TITLE></HEAD> <SCRIPT LANGUAGE="VBScript"> <!-- Sub cmdChange_nClick    Dim d                   'Create a variable    Set d = CreateObject("Scripting.Dictionary")    d.Add "0", "Athens"     'Add key and Project    d.Add "1", "Belgrade"    d.Add "2", "Cairo"    For Each I in d        Document.frmForm.Elements(I).Value = D.Item(I)    Next End Sub --> </SCRIPT> <BODY> <CENTER> <FORM NAME="frmForm" <Input Type = "Text"><p> <Input Type = "Text"><p> <Input Type = "Text"><p> <Input Type = "Text"><p> <Input Type = "Button" NAME="cmdChange" VALUE="Click here"><p> </FORM> </CENTER> </BODY> </HTML>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.