"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:

<!-- array_foreach.html
 - Copyright (c) 2015, HerongYang.com, All Rights Reserved.
<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"

   ' Retrieving array elements
   document.writeln("Web sites:")
   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
Web sites:

Noticed anything interesting? This VBScript example confirms that:


Table of Contents

 About This Book

 Introduction of VBScript - Visual Basic Scripting Edition

 Variant Data Type, Subtypes, and Literals

 Arithmetic Operations

 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

 Built-in Functions

 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)


 Full Version in PDF/EPUB