VBScript Tutorials - Herong's Tutorial Examples - v6.02, by Herong Yang
"For Each" Statement Example
This section provides a tutorial example on how to use a 'For Each' statement to loop through all elements in an array.
In previous sections, we learned that a "For Each" statement can used to loop through all elements in an array quickly.
To show you how the "For Each" statement works, I wrote the following VBScript example, array_foreach.html:
<html> <body> <!-- array_foreach.html - Copyright (c) 1998 HerongYang.com. All Rights Reserved. --> <pre> <script language="vbscript"> ' Creating a dynamic array Dim aSite() ReDim aSite(2) aSite(0) = "yahoo" aSite(1) = "netscape" aSite(2) = "microsoft" document.writeln("Is aSite an array? " & IsArray(aSite)) document.writeln("Lower bound of aPrime = " & LBound(aSite)) document.writeln("Upper bound of aPrime = " & UBound(aSite)) ' Resizing the array ReDim Preserve aSite(8) aSite(8) = "ibm" ' Updating array elements For Each sSite In aSite sSite = sSite & ".com" Next ' Retrieving array elements document.writeln("Web sites:") For Each sSite In aSite document.writeln(" " & sSite ) Next </script> </pre> </body> </html>
Here is the output:
Is aSite an array? True Lower bound of aPrime = 0 Upper bound of aPrime = 2 Web sites: yahoo netscape microsoft ibm
Noticed anything interesting? This VBScript example confirms that:
Table of Contents
Introduction of VBScript - Visual Basic Scripting Edition
Variant Data Type, Subtypes, and Literals
Numeric Comparison Operations and Logical Operations
String Operations - Concatenation and Comparison
Variable Declaration and Assignment Statement
Expression and Order of Operation Precedence
Statement Syntax and Statement Types
►Array Data Type and Related Statements
"Dim x()" - Declaring Array Variables
"x(i)" - Accessing Array Elements with Indexes
"Dim x(n)" - Fixed-Size Array Example
"Dim x()" - Dynamic-Size Array Example
"Erase" Statement - Removing All Elements in an Array
Data Type "Variant()" - Array of Variant Values
Array References and Array Assignment Statements
Conditional Statements - "If ... Then" and "Select Case"
Loop Statements - "For", "While", and "Do"
"Function" and "Sub" Procedures
Inspecting Variables Received in Procedures
Error Handling Flag and the "Err" Object
Regular Expression Pattern Match and Replacement
scrrun.dll - Scripting Runtime DLL Library
IE Web Browser Supporting VBScript