"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:
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
' Creating a dynamic array
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"
' Retrieving array elements
For Each sSite In aSite
document.writeln(" " & sSite )
Here is the output:
Is aSite an array? True
Lower bound of aPrime = 0
Upper bound of aPrime = 2
Noticed anything interesting? This VBScript example confirms that:
- "For Each" statement creates a copy of the current element in the temporary variable
at each iteration. You can not update element values through this temporary variable.
My "Updating array elements" code block updated only the temporary variable, not array elements.
Table of Contents
About This Book
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
What Is an Array?
"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
►"For Each" Statement 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
Creating Your Own Classes
IE Web Browser Supporting VBScript
IIS ASP Server Supporting VBScript
WSH (Windows Script Host)
PDF Printing Version