• »
• Technology»
• Computers & Software»
• Computer Science & Programming

How to write a Do While loop in Visual Basic

Updated on June 23, 2012

This Hub provides an easy and simple to follow example for beginner training on looping techniques in Visual Basic. Refer to the attached diagram as we move through it. Starting at the top, we see the programming section defined as a subroutine, named “looptest”.

The next set of lines “dimensions”, or declares the variables we will use:

“a”: we will build a string as the code passes through the loop several times. “a” is that string variable.

“crtn”: another string, in which we will place “vbCrLf”. It will then be made part of the string “a” as we build it, to move down to the next line before displaying the next number, “x”, of the string. vbCrLf performs a carriage return. The result, a “vertical”, or “up and down” string is built.

“x”: an integer “condition check” variable for the loop, to determine when the loop will be continued or exited (finished). It will also be operated on within the loop.

Next 2 lines:

x = -2

a = ""

They give variables “x” and “a” initial values. If these lines had been neglected, it would not have been a disaster. “x” would have taken on the initial value 0, which would have changed the first output result. “a” would have assumed the null, or empty string. It would have taken on the same value I assigned to it, “”, which means nothing (empty).

Now the looping lines:

Do While x <= 10

x = x + 2

a = a & x & crtn

Loop

“x” starts out at -2. The loop will do its thing, from top, as long as x <= 10. Walk through for the first trip: “x” becomes x + 2 = -2 + 2 = 0. “a” then becomes “a” concatenated with “x”, then the output will move down to a blank line to continue building the string on the next pass through the loop. After this first pass, we simply get “x”, or “0”, on the first line. When we get to the “Loop” statement, execution goes back up to the “Do While” line. It checks to see if x <= 10. If so, it moves down through the loop again, and continues to build the “vertical” string, “a”.

Once the loop is exited, we see the next line:

“MsgBox (a)”

This simply displays a message box, showing the completed string “a” which the loop built. Each number in the vertical column represents what “a” contained that iteration through the loop (see diagram).

1

0

2

14

165

18

269