vbscript Arrays and Loops 7. For Each loop.


Example

You cannot alter the array's contents through the loop variable because it's a temporary each element is being assigned to.

Dim cars(2) 'collection of different cars
Dim trace 'track iteration details
cars(0) = "Ford"
cars(1) = "Audi"
cars(2) = "Prius"
For Each car in cars
    trace = trace & car & " temporarily changed to "
    car = "Jeep" 'affects car but not the cars array
    trace = trace & car & vbNewLine
Next

MsgBox trace 'show what happened during the loop

Dim jeeps : jeeps = 0
For Each car in cars
    If car = "Jeep" Then jeeps = jeeps +1
Next

MsgBox jeeps & " of the cars are Jeeps."