For Each… - VBScript
Overview
For Each… iterates through the elements of a collection, performing an action for each item. It’s commonly used for processing arrays and collections of objects.
Syntax
For Each element In collection
[Actions]
Next
where:
- element is a variable representing each item in collection.
- collection is the iterable collection of elements.
Options/Flags
None.
Examples
Simple Usage
Dim myArray = Array(1, 2, 3, 4, 5)
For Each item In myArray
WScript.Echo item
Next
Complex Usage
Set myCollection = CreateObject("Scripting.Dictionary")
myCollection.Add "Key1", "Value1"
myCollection.Add "Key2", "Value2"
For Each key In myCollection.Keys
WScript.Echo key & ": " & myCollection(key)
Next
Common Issues
- Ensure the iterable collection is valid and contains elements.
- Avoid modifying the collection within the loop as it can lead to unpredictable results.
Integration
For Each… is often used in conjunction with other VB Script commands, such as:
- WScript.Echo: To print loop results to the console.
- CreateObject: To create collection objects.
- If…Then…Else: To perform conditional actions based on loop elements.
Related Commands
- For…To…Next: Iterates through a specified numeric range.
- While…Wend: Iterates as long as a condition is true.