FOR EACH ... NEXT iterates statements for each element in a collection.
👉 FOR EACH ... NEXT can be invoked only with COM/ActiveX objects.
Syntax:FOR EACH Element IN Collection Statements NEXT [Element] Parameters:
|
Do not use nested FOR EACH ... NEXT loops as they will not work as expected.
Here is a simple example that shows how BCX COM uses FOR EACH to iterate through a collection to find, in a string, matches to a pattern.
👉 Because Microsoft support for VBScript is now limited to X86 processing, this example must be compiled as 32 bit.
BCX_SHOW_COM_ERRORS(TRUE) '---------------[ R E S U L T S ] ------------------ ' ' Match found at position 0. Match Value is 'IS1'. ' Match found at position 4. Match Value is 'is2'. ' Match found at position 8. Match Value is 'IS3'. ' Match found at position 12. Match Value is 'is4'. ' '--------------------------------------------------- PRINT Rx$("is.", "IS1 is2 IS3 is4") FUNCTION Rx$ (Pattern$, MainStr$) DIM vbrx AS OBJECT DIM Matches AS OBJECT DIM Match AS OBJECT DIM RetStr$ DIM Tmp$ DIM i vbrx = CREATEOBJECT("VBScript.RegExp") WITH vbrx .Pattern = Pattern$ ' Set pattern. .IgnoreCase = TRUE ' Set case insensitivity. .Global = TRUE ' Set global applicability. END WITH SET Matches = vbrx.Execute(MainStr$) FOR EACH Match IN Matches ' Iterate Matches collection. RetStr$ = RetStr$ & "Match found at position " i = Match.FirstIndex RetStr$ = RetStr$ & STR$(i) & ". Match Value is '" Tmp$ = Match.Value RetStr$ = RetStr$ & Tmp$ & "'." & CRLF$ NEXT SET Match = NOTHING SET Matches = NOTHING SET vbrx = NOTHING FUNCTION = RetStr$ END FUNCTION
Match found at position 0. Match Value is 'IS1'. Match found at position 4. Match Value is 'is2'. Match found at position 8. Match Value is 'IS3'. Match found at position 12. Match Value is 'is4'.