martin2k

ForumsVB6GamesSoftwareDirectoryHTMLArticlesBlogContact

Using For...Next Statements


 

Home

Read and add posts to the Visual Basic 6.0 Forums

Download some of my programs and OCXs

Read the Tips here

The old style forum is still available here

Contact


 

Beginner Tip

You will now learn how to use the For...Next statements.  Unlike Do..Loop statements, which run commands continually until the condition specified occurs, For...Next statements loop commands a set number of times.

1. Open Visual Basic 6.0 and start a new Standard EXE project.  Click here if you don't know how to do this.

2. On the General combo box of the code window, choose Form and the following text will appear:

Private Sub Form_Load()

End Sub

3. Here are some simple examples of using the For...Next statement (use all of these examples in between the above two lines):

Dim i As Integer
For i = 1 To 10
MsgBox "Hello number " & i
Next i

Me.Caption = i

The above code creates an integer called 'i', which has a starting value of 0.  The second line sets the value of 'i' to 1 and the command will be run 10 times as specified by To.  The word 'Hello' will be shown in a message box.   You must put 'Next i' at the end.

Dim i As Integer
For i = 0 To 10 Step 2
MsgBox "Hello number " & i
Next i

Me.Caption = i

This example has extra code on the second line.  The optional Step keyword allows to increment the loop by a number other than the default of 1.  In the above case, the loop will start at 0, then go to 2, then 4 and so on until it reaches 10.  The Step keyword can also have a negative number if you need to countdown e.g. For i = 10 To 0 Step -1.  If you need to come out of a For...Next loop before it finishes, use the code 'Exit For' and the execution will continue after the Next keyword.

Dim i As Integer, tmp, tmp2
tmp = Split("Hello|this|is|my|first|program", "|")

For Each tmp2 In tmp
MsgBox tmp2
Next

The above code uses the Split function to split the sentence up and store it into the 'tmp' array.  Afterwards, the code looks for each string in the array and displays it in a message box.

Dim i As Long
    Open "C:\windows\desktop\files.txt" For Output As #1
        For i = 0 To File1.ListCount - 1
            Print #1, File1.Path & "\" & File1.List(i)
        Next i
    Close #1

This code looks at every item in a file list box and saves the full filename to a file called 'C:\windows\desktop\files.txt'.


blog comments powered by Disqus

Archived Comments

From: twinkle
Date: Thursday, February 12, 2009 at 09:37:32
Comments: thanxx. it help me a lot.
 
From: jagathwalpola
Date: Thursday, November 2, 2006 at 07:52:06
Comments: thank you very much!
 
From: bogs
Date: Tuesday, March 8, 2005 at 06:45:00
Comments: thank u very much......... even though i'm not sending u questions, still i learned a lot from u trough comments of others......... i ask u next time....
 
From: Dave
Date: Saturday, July 17, 2004 at 00:33:41
Comments: Well, the Code Above is pretty close, but if you want the file to continue adding to it, every time its run you would use Open "Filename.txt" for Append as #1
Print #1, DATA
 
From: Richard
Date: Wednesday, February 18, 2004 at 04:01:54
Comments: I need to know how to repeat a sub a certain number of times. The number of times is written in "textbox1". I dont know how to do it and I would be grateful if someone could help me. Please send me an email as i probably wont check this! Thanks! - Richard
 
Reply:

The following code will do this:

Private Sub Command1_Click()
Dim i As Integer

For i = 1 To Val(Text1.Text)
    ShowTimeDate
Next i
End Sub


Sub ShowTimeDate()
MsgBox Now()
End Sub

 
From: david meyrick
Date: Sunday, February 15, 2004 at 20:10:02
Comments:

trying to run a program where i can generate six random numbers for the lottery. i have managed to generate these numbers okay but i don't no how to go about coding it so that the same number doesn't appear twice. i also need to put them in order from lowest to highest. i have tried a number of combos' but can't figure it. i guess it would be best to do a loop but i thought it would be easier to use an if statement first.

Option Explicit

Private Sub Command1_Click()
    Dim RandomnumberArray(5) As String * 2
   
        Label1(0).Caption = Int((49 * Rnd) + 1)
        Label1(1).Caption = Int((49 * Rnd) + 1)
        Label1(2).Caption = Int((49 * Rnd) + 1)
        Label1(3).Caption = Int((49 * Rnd) + 1)
        Label1(4).Caption = Int((49 * Rnd) + 1)
        Label1(5).Caption = Int((49 * Rnd) + 1)
       
End Sub


Private Sub Command2_Click()
End
End Sub

 
Reply:

The best way to do this is to create a Sub that shuffles an array of numbers randomly.  The following example shuffles the numbers 1 to 49 and then a message box is displayed showing the first 6 numbers in the array.

Dim Lottery(1 To 49) As Integer

Private Sub Command1_Click()
ShuffleArray 1, 49, Lottery()

MsgBox Lottery(1) & ", " & Lottery(2) & ", " & Lottery(3) & ", " & Lottery(4) & ", " & Lottery(5) & ", " & Lottery(6), vbInformation, "Lottery Numbers"
End Sub


Sub ShuffleArray(Smallest As Integer, Largest As Integer, NewArray() As Integer)
Dim i As Integer, j As Integer, t As Integer

Randomize

For i = Smallest To Largest
    NewArray(i) = i
Next i

For j = Largest To Smallest Step -1
    i = Int(Rnd * j) + 1
    t = NewArray(j)
    NewArray(j) = NewArray(i)
    NewArray(i) = t
Next j
End Sub

 
From: chaitanya
Date: Thursday, January 15, 2004 at 15:54:13
Comments: hi,
i want to perform one loop operation(i= 1 to 100) and i want to store all the values in the file.i am able to do it for a single time(i mean single value).can any please tell me how to append the values to a file if i am performing loop operation.
 
Reply:

You can achieve this with the following code:

Dim i As Integer

Open "C:\numbers.txt" For Output As #1
    For i = 1 To 100
        Print #1, Trim(Str(i))
    Next i
Close #1

 
From: michelle
Date: Monday, March 24, 2003 at 13:54:33
Comments: Please tell me how to set a range! Should I use end if or loop?!?! Thank you
 
Reply: Are you trying to make code loop a certain number of times?

If you are then try this code:

Dim i As Integer
For i = 1 To 10
    'code
Next i

This code will loop 10 times.


Martin Allen 1999 - 2011.  Last updated Monday 08 August 2011 07:28:14 PM +0100.