Search notes:

VBA statement: for

for is a looping statement.

for n = 1 to y

' runVBAFilesInOffice.vbs -word %CD%\for -c main

sub main()

  for i = 5 to 10
    selection.typeText i & " "
  next i

  selection.typeText chr(13)

  for i = 20 to 100 step 15
    selection.typeText i & " "
  next i

  selection.typeText chr(13)

  for i = 1000 to 500 step -125
    selection.typeText i & " "
  next i

  activeDocument.saved = true

end sub
Github repository about-VBA, path: /language/for.bas
Such a for loop can be exited with exit for.

for each

The for each elem in coll statement runs a series of statements for each element in a collection.
The iteration can be terminated before the last element was reached with exit for.
If the type of the collection is an array, the type of elem must be variant.
' runVBAFilesInOffice.vbs -word %CD%\for_each -c main

option explicit

sub main()

  dim item as variant
  for each item in array("foo", "bar", "baz")
    selection.typeText item & chr(13)
  next item

  activeDocument.saved = true

end sub
Github repository about-VBA, path: /language/for_each.bas
See also for each in on collections and on dictionaries.
The for each statement can also be used to iterate over each cell in an excel range.
In order to create a custom behaviour for for each … in statements, the IEnumVARIANT interface must be implemented.

See also

VBA statements
The C# statement foreach … in

Index