I have found definitions for these terms but they do not quite make sense to me. Could someone explain them in laymans terms to a rookie?
Thanks!
Printable View
I have found definitions for these terms but they do not quite make sense to me. Could someone explain them in laymans terms to a rookie?
Thanks!
For Next and For Each Loops are ways of running code several times changing one variable and giving it a different value evert time it runs
imagine you want to add up all the numbers from 1 to 100
one way is
but thats a lot of typing and you can't vary how much you want to add up to without altering all that codeCode:
dim Total as integer
Total = 0
Total = Total + 1
Total = Total + 2
Total = Total + 3
'I Cant Be arsed to put the rest in
Total = Total + 99
Total = Total + 100
MsgBox Total
a better way would be
a For Next loop does this for youCode:
dim Total as integer
Dim i as integer 'Counter Variable
Total=0
i=1
Start::
Total=Total+i
i=i+1
IF i<=100 then goto Start::
msgbox Total
this code is exactly the same as
N.B. i doesnt have to be an integer it can be any numeric variable (long, Byte Double etc.)Code:
dim i as integer
dim Total as integer
Total = 0
For i= 1 to 100
total=total+1
next i
msgbox total
and you dont always have to add 1 each time if you want to add up all the even numbers from 1 to 100 just replace for i = 1 to 100 with For i = 2 to 100 step 2
For Each loops are used for collections
Say you have a collection of Peoples Names called collNames and you want to say hello to all of them (These aren't very goot examples of usefull things to do in VB)
try this
this will put up a messagebox saying hello to everyone in your collectionCode:
dim varTemp as variant
for each vartemp in collNames
msgbox "Hello " & vartemp
next vartemp
N.B. varTemp must be a variant otherwise VB Complains
If you havn't met collections yet don't worry about them, I hardly ever use them and they're slow anyway.
Hope this helps