FOR EACH … ENDFOR Command Examples
The following examples demonstrate how FOR EACH is used to enumerate elements in a Visual FoxPro array, an OLE array, and a set command buttons assigned to an object array.
In the following example, a Visual FoxPro variable array is created and FOR EACH is used to display the contents of each element in the array.
DIMENSION cMyArray(3)
cMyArray[1] = 'A'
cMyArray[2] = 'B'
cMyArray[3] = 'C'
FOR EACH cMyVar IN cMyArray
? cMyVar
ENDFOR
In the following example, an instance of Microsoft Excel is created, and a new workbook is added. FOR EACH is used to display the name of each worksheet in the workbook. This example requires that Microsoft Excel be properly installed on the machine on which the example is run.
oExcel = CREATE("Excel.Application")
oExcel.Workbooks.ADD
FOR EACH oMyVar IN oExcel.sheets
? oMyVar.name
NEXT oMyVar
In the following example, five command buttons are placed on a form. FOR EACH is used to display the buttons on the form and specify the captions, font styles and positions of each button.
PUBLIC oMyObject
oMyObject = CREATEOBJECT("frmTest")
oMyObject.SHOW
DEFINE CLASS frmTest AS FORM
Height = 200
DIMENSION MyArray[5]
PROCEDURE Init
FOR i = 1 to 5
THIS.AddObject('THIS.MyArray[i]',;
'COMMANDBUTTON')
ENDFOR
****** FOR EACH - NEXT ******
FOR EACH oButton IN THIS.MyArray
oButton.Visible = .T.
NEXT
****** FOR EACH - NEXT element ******
FOR EACH oButton IN THIS.MyArray
oButton.FontBold = .T.
NEXT obutton
j = 1
****** FOR EACH - ENDFOR ******
FOR EACH oButton IN THIS.MyArray
oButton.top = j * 30
j = j + 1
ENDFOR
****** FOR EACH - ENDFOR element ******
FOR EACH oButton IN THIS.MyArray
oButton.FontItalic = .T.
ENDFOR obutton
j = 1
****** EXIT ******
FOR EACH oButton IN THIS.MyArray
oButton.Caption = "test" + str(j)
j = j+1
IF j > 3
EXIT
ENDIF
NEXT
j = 1
****** LOOP ******
FOR EACH oButton IN THIS.MyArray
IF j > 3
LOOP
ENDIF
j = j + 1
oButton.Left = 25
NEXT
ENDPROC
ENDDEFINE