March 22, 2020

VBScript tutorial 5 | For Next Statement

This is the next tutorial in the VBScript Tutorials for Beginners. This VBScript beginner tutorial explains a VBScript conditional statement, the VBScript For Next statement, which is a loop statement in VBScript. Please view the VBScript tutorial 5 or read on... What is loop in VBScript? A loop is a code block that can run repeatedly, depending on a condition. For Next loop in VBScript runs a fixed number of times. Let us see VBScript for loop examples.

'VBScript code
Option Explicit
Dim i
Call Loop1
Call Loop2
Call Loop3

Sub Loop1
For i = 1 to 5
    ' All statement(s) between For and Next statements are run for each value of i from 1 to 5.
    MsgBox "The current value of i is " & i, vbInformation, "For Loop1"
Next
End Sub

Sub Loop2
For i = 1 to 10 Step 2
    ' The statement(s) are run for the values of i from 1 to 10, increasing by 2 every time.
    MsgBox "The current value of i is " & i, vbInformation, "For Loop2"
    ' Uncomment the following If Then statement to exit the For loop when i is 5.
    'If i = 5 Then Exit For
Next
End Sub

Sub Loop3
For i = 10 to 1 Step -2
    ' The value of decreases from 10 to 1, by 2 every time.
    MsgBox "The current value of i is " & i, vbInformation, "For Loop3"
Next
End Sub

Next, let us learn about the For Each loop in VBScript. It runs a code block on each value in an array or a collection. Let us see a VBScript for each loop example. This VBScript code lists the files present in the given folder.

' VBScript code
Option Explicit
' The following statement causes the VBScript to keep running even after an error, until the last statement.
On Error Resume Next
Dim objFSO, objFolder, objFile
' VBScript CreateObject function creates a VBScript object, objFSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")
' GetFolder function gets the VBScript object for a given folder.
' Note: give a folder path that exists.
Set objFolder = objFSO.GetFolder("E:\Training\VBScript\Files")
' VBScript For Each loop runs for each file in the folder. There may be any number of such files.
For Each objFile in objFolder.files
    ' Display the name property of the file object.
    MsgBox objFile.name
    ' Instead of objFile.name, we may give objFile.path or objFile.size.
Next

Want to learn with more details and a more complex example? Please view my VBScript tutorial 5. Thank you.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.