Developer Documentation Library > Scripting > mrScriptBasic overview > mrScriptBasic language reference > Statements > For Each...Next
For Each...Next
A For Each...Next structure repeats a group of statements for each element in an array or collection.
For Each element In group
[Exit For]
Variable used to iterate through the elements of the collection or array.
Name of an object collection or array, or an expression that returns an object collection or array.
One or more statements that are executed on each item in group.
The For Each block is entered if there is at least one element in group. Once the loop has been entered, all of the statements in the loop are executed for the first element in group. As long as there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.
Exit For can be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements can be placed anywhere in the loop. Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.
This example uses a For Each...Next statement to loop through the VariableInstance objects in an MDM Document, writing their English (United States) question texts to a text file. To run this example using the mrScript Command Line Runner, you need to use the /m: option to specify an .mdd file.
Dim fso, txtfile, myObject
Set fso = CreateObject("Scripting.FileSystemObject")
Set txtfile = fso.CreateTextFile("variables.txt", True)

For Each myObject in MDM.Variables
This example asks each question in a loop, for each question in another element.
Dim Q
For Each Q in Rating
See also