Loops
[ Using VB ]
In order to save a lot of time and space, a programmer will find loops to be very useful. The main thing a loop does is run the same code X amount of times. There are 2 basic kinds of loops that you will need to know. Of course, each has it's own advantages and disadvantages. Your job is to choose which one works best for your particular program.
The Do Loop is a good loop to use if you do not know how many times you want to loop. For example, if you're reading a text file that is different lengths every time you open it, then you'll want to read till the end of it. Where is the end? You can't put the number of characters or the number of lines in the code 'cause this could change. So, the Do Loop can go through the file a line at a time until it gets to the end (EOF = End Of File).
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
or
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
The condition can be either True or False. If the condition is true, the you can either Loop While True or Loop Until True. If you were searching a file for a name, then you'd need to quit when that name was found. It may look like this...
Sub Command1_Click ()
Dim strName As String, strInput As String, blnFound As Boolean
strName = "Jessica" 'Name To Search For
Open "C:\Windows\Address.txt" For Input As
1 'Opens Data File
Do 'Start The
Loop
Input #1, strInput 'Get
a new line of file.
If strInput = strName Then
'If the name is found...
blnFound = True 'Set
blnFound to True
End If
Loop Until blnFound = True Or
EOF(1) 'Loop back to the "Do" line
End Sub
If the name is found then the variable blnFound will equal true through the rest of the code. If the loop reached the end of the file without finding strName then blnFound = False till the end.
The For Next Loop is a good loop to use if you know how many times to loop it. If you have an array of command buttons and want them all to disappear, then you can use this loop.
Sub Command1_Click ()
Dim i As Integer
For i = 0 To 50
cmdMenu(i).Visible = False
Next i
End Sub
This code will make all 51 command buttons disappear with a lot less code.