VB6 Tutorial 21: For ... Next Loops

Posted On 2018-04-06 by VB6Boy
Keywords: visual,basic,vb6,visualbasic,tutorial,basic,beginner
Tags: VB6 Tutorials Windows
Views: 52


Looking for the more of the VB6 Tutorial? Here is the tutorial index.

In this lesson, I'll take you through the For Loop structure with a couple of simple code examples. Undoubtedly the For...Next loop structure is the most useful among others.

Example

To print 0 to 10.

Dim i As Integer
For i = 0 To 10
    Print i
Next i

When the value of i is 0, the Print statement is executed then i is incremented to 1. It checks whether the value of i is from 0 to 10. If it satisfies, the Print statement is executed again. In this way, the loop goes on until the value of i exceeds 10. Every time, the value of i is incremented by 1.

Example

To print 0 to 6 in steps of 2.

Dim i As Integer
For i = 0 To 6 Step 2
    Print i
Next i

Every time, the value of i is incremented by 2.

Output:

0
2
4
6

Example

To print in descending order from 10 to 0 in step of -3.

Dim i As Integer
For i = 10 To 0 Step -3
    Print i
Next i

Every time, the value of i is decremented by 3.

Output:

10
7
4
1

Exit For and Exit Do statement

A For Next Loop can be terminated by an Exit For statement and a Do loop can be terminated by an Exit Do statement.

Example

Exit For statement.

Dim i As Integer
For i = 0 To 10
    If i = 3 Then
    Exit For
    End If
Print i
Next i

Output:

0
1
2

Example

Exit Do statement

Dim num As Integer
num = 0
Do While num < 10
    Print num
    num = num + 1

    If num = 4 Then
        Exit Do
    End If
Loop

Output:

0
1
2
3

Looking for the more of the VB6 Tutorial? Here is the tutorial index.


About the Author

has posted a total of 101 articles.


Comments On This Post

No comments on this post yet!


Do you have a thought relating to this post? You can post your comment here. If you have an unrelated question, you can use the Q&A section to ask it.

Or you can drop a note to the administrators if you're not sure where you should post.


Your IP address is:54.81.71.68

Before you can post, you need to prove you are human. If you log in, this test goes away.


Code Links