Visual Basic 6.0 – Tutorial 2

A picture of Mustang Sally, my dog and friend.

Learning How to Use For Loops and Random Numbers

8-22-09

For this application I am assuming that you have the Visual Basic IDE loaded and have selected a
standard EXE for your project.

See my "Visual Basic 6.0 - Tutorial 1" for basic beginner instructions.

The first thing that I always like to do is save the project with the name that I choose. For this project, I will call it "Lotto".

Save the form and the project file with the name "Lotto".

This application will use a random number generator to create 6 random numbers between zero and fifty-two. I use these numbers because that is the actual way that the lotto is done where I am. You can study the code and adjust the configuration to fit the lotto numbers in your area. We are actually going to write code this time, so put on your thinking cap!

The first control that we need to put on the form is the text box. Place a text box any place on the form. Now, right click on the text box and click on the copy option in the drop down box. Now, right click on the form and click paste from the drop down box. The IDE will complain that you already have a text box called text1 and asks if you want to create an array. Click yes on the popup.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

The new text box will appear in the upper left corner. Right click again on the form and click paste again. Do this three more times. This will give you a total of six text boxes with the Text1 inside the box. Click down and drag on the (the one that you can see) and drag it over to the far right.I have widened my default form so that I may have room for all of the text boxes to fit side by side. I have also shortened the text boxes.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

This is what my final form with text boxes looks like.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

The text boxes are equally sized and evenly spaced across the form.  Now lets add a button control. Click on the button control from the tool box and place it like this on the form.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

The controls are a little low so lets select them all and move them up in the form. Click down the left mouse button on upper left side of the form in the working area and drag the mouse to the lower right side of the form. You will see a dotted line rectangle appear as you drag and when you release the left mouse button, all of the controls in the window are selected. All you need to do now is click down on any of the controls and maintain the left mouse button down and drag the controls up higher on the form. Below shows all of the controls selected.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

Below shows all of the controls moved up to make room for the label.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

Now lets place a label below the button. Make it start in the same place and make it just as long as the buttons, but a little wider. I will show a screen shot a little later at the end of the project. Now, lets write some code. Double-click on the form in a place where there is no control placed, otherwise, you will get a code window for that control. Make sure that the automatic text in the code window says:

Private Sub Form1_Load()

(This is the sub heading. Place the code that we are going to write in here.)

End Sub

The reason that we copied the text box onto the form the way that we did was so that it would create an array of text boxes using the same name. I will show you the benefit of doing this next. Place this code in between the sub heading and the "End Sub", as shown above, on your code page.

Variables are used to store information in a program so that you can use the information in different places in your code. There are many different types of variables used and we will learn each type that we use in this program, one at a time.

The first line of code is telling VB that we are declaring the variable name "Count" as an integer type variable. The integer variable, as you may know from math or algebra, is a number that cannot have a fractional part. The number used with this variable can't have a decimal behind it with another portion, such as 5.2. The number 5.2 is not an integer. The integer part of 5.2 is 5 and the rest is fractional.

The variable "Count" can only be of integer value because thats the way we declared it with the Dim statement, and we are going to use it as a counting mechanism in our code.That is why I called it "Count". You may name your variables anything that you wish, like George or Chrysanthemum. The variables do not require that you capitalize the first letter, either In fact if you declare a variable named "george", every time that you enter "George" in your code, VB will automatically change it to "george" because that is the way that you declared it. That is enough about declaring variables.

We now have a variable named "Count" to use in our code, so lets use it!

The code below uses a counting function called a For.. Next loop.

The beginning of the function starts with:

For Count = 0 To 5

You see, we are already using our variable "Count". The code that you want counted is next:

Text1(Count).Text = ""
Text1(Count).Font = "Tahoma"
Text1(Count).FontBold = True
Text1(Count).FontSize = 12
Text1(Count).Alignment = 2

Text1 is the name of an object (a control) that we are using on Form1, so we can write code to change the properties. We are doing it with code this time as opposed to changing the properties in the properties window (refer to Tutorial 1.) This is a better way to set property values, because it sets them all when you run the software rather than statically setting the properties in the development window.

Some programmers say that this is the most proper way to do property settings. The code above is setting the properties of the text boxes by enumerating them. Each TextBox1 that you placed on the form has an index associated with it. This number is the number that was assigned each time you copied a new text box to the form. Do you remember when it asked you if you wanted to create an array You should have clicked the "Yes" button when the message popped up on your screen We now have an array of text boxes to work with using the For-Next loop. By going through the loop "Count" times, we are setting the properties of each text box to the same values.

The first property value is the Text value:

Text1(Count).Text = ""

This is what is actually in the box, the actual text that will display. We are setting the value to "" which means an empty string. Text values are string values. I will explain string values later, but text is a string value.

The next property that we set is the Font property:

Text1(Count).Font = "Tahoma"

This tells VB which font to use for the text that is going into the text box. Tahoma is a common font for MS Windows.

The next property that we set is the FontBold property:

Text1(Count).FontBold = True

You'll notice that this is a True or False setting. (This type of variable or setting is called Boolean, more in a later tutorial.) We are setting the property value to True so that our text font will also be bold. The default value for this setting is False, and this is why we are setting it to True. Most properties have a default value. This means that it is already set to this value automatically and if you want something different, you have to change it.

The next property that we set is the FontSize property:

Text1(Count).FontSize = 12

We are setting this value to 12. Just a note about property values; if you set the property value to something that is not available, you will probably get an error. Tahoma font has values from 8 to 36 in +2 form (in other words, 8, 10, 12, 14 - 36) for the FontSize property. You can open MS Word and look at the values available for Tahoma font sizes.

The next property that we set is the Alignment property:

Text1(Count).Alignment = 2

This tells VB where to place the text inside the text box. A "2" value tells VB to place the text in the center of the box A "0" value would be left align and a "1" value would be right align.

Finally, to close this portion of the code, we must add the:

Next Count

This is to tell VB that we are done counting and to go back to the For part to see if the count is finished. If the count is finished, the code following this statement will be executed. We told it to count from zero to five (thats six times, the exact number of text boxes that we have.)

Here is the code in its entirety:

REM Declare the variable for counting our text boxes.

Dim Count As Integer

REM Start counting from 0 because our array starts counting from 0

For Count = 0 To 5

REM Set the text inside of the text box to nothing.

Text1(Count).Text = ""

REM Set the text font that will be displayed to the Tahoma font.

Text1(Count).Font = "Tahoma"


REM Set the font characteristic to bold
Text1(Count).FontBold = True

REM Set the size of the font to size 12.
Text1(Count).FontSize = 12

REM Align the text inside the box so that it appears in the center
Text1(Count).Alignment = 2

REM This is where the program returns back up to the FOR part to see
REM if it is finished counting. If it is, start the code immediately
REM following this statement, which in this case is End Sub.

Next Count

End Sub

By using an array of text boxes, we can use the For .. Next with a counting variable in the index of the text box name, i.e.; Text1(Count). The Count variable holds the number of the iteration of the For .. Next. Each time the loop goes through the code, it adds a number to the loop counter variable, in this case the variable is called Count.

The first round through the loop, the variable Count is set to 0 (zero) and the properties are set for the text box named Text1(0), because the variable Count is in the index. The next round through the loop, the variable Count is set to 1 (one) and the Text1(1)text box properties are all set, and so on and so forth. After the loop counter reaches 5 (five) which is what we told it to count to, the loop is finished and the code proceeds on to the next line of code, which is End Sub in this case.

I have added lines in the code that begin with REM. These are remarks that coders should use in their code to explain what they are doing with the code. Most of the time, months or even years after you have written your code, these remarks will remind you of what you were doing with the code. For most professional software programmers, this is absolutely required, so get used to writing remarks!

We now need to write some code for the button, Command1. (These names for these controls are the default names that VB assigns to these controls when you drop them onto the form.) They can also be changed in the same manner as the text box properties. More on this later.

Double-click on the project window where it says Form1(lotto.frm) over to the upper right of the work area. The heading in the project window is labeled Project Project1. By clicking on the form1(lotto.frm) object, the form window should re-appear like the picture below.

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

Double-click on the Command1 button and, presto, the codes window is back again, only now you have:

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

<<Clisk here to see the screenshot, then use the back navigate to get back here.>>

The code in the window where VB placed you looks like this:

Private Sub Command1_Click()

End Sub

Use the same rules as before, place the code between the heading and the End Sub like below. I will explain the code using the REM statements. Note: If you cut and paste this as text into your IDE code, you may see errors for the REM statements because some of the characters may not be allowed for REM statements. The remarks, if done correctly will turn green on your screen.

Private Sub Command1_Click()

REM Declare 3 variables as integers to be used in our code for this
REM subroutine only.

Dim Count, Results, SubCount As Integer

REM Start the For.. Next Loop and count to five again because we are REM still working with our six text boxes.

For Count = 0 To 5

REM Use the function that will create a random number based on
REM the Now() function. Now() function will return the
REM current date and time in a large number called a TimeSerial
REM number that Windows uses to keep the correct time.
REM By making a random number based on this moment in time, we
REM will ensure that we will get returned a truly random
REM number.

Randomize Now()

REM Set the returned value of the result of the random number
REM multiplied times 54, which is our highest number that we
REM can use for generating our lotto numbers. Also we
REM want to make sure that the number that is returned is an integer
REM number and that is why we have Int in front of (Rnd * 52).
REM Our variable can only handle integer numbers, remember

Results = Int(Rnd * 52)

Rem Now, we set the value of each text box using the loop
REM value, (remember the way we set the property
REM values earlier?). The value of Results + 1 will appear in each
REM text box as the loop gets iterated. We add 1 to the results
REM because, in our lotto, the numbers start at 1. If your
REM lotto numbers include 0, then do not add 1 to the results.

Text1(Count).Text = Results + 1

REM This checks to see if the variable Count is not equal to 0.
REM If the value of Count is equal to 0, then the code inside the
REM If Then structure will be executed. The reason that we
REM are doing this is because we want to make sure that we
REM dont duplicate the same number that is in another box.
REM This eliminates the first box for checking, because it is an
REM original number because it was first to get assigned a
REM number. Does this make sense?

If Count <> 0 Then

REM We start another loop, inside the loop that we are
REM already running. This is called nested loops. We are
REM now using the SubCount variable for this loop. We
REM are counting to 1 less than the previous loop counter
REM in this loop. The reason that we are doing this is to
REM check the current random number against all of the
REM previous numbers to ensure that we do not duplicate
REM another number. We are checking the current number
REM against the value that is in each previous text box.

For SubCount = 0 To Count - 1

REM Now checking the current number against the past number in the
REM text box with the index value.
REM Notice that we are changing the type of data back into an integer by using
REM the Int in front of the (Text1(SubCount).Text, because text is a string value.
REM We are also subtracting 1 from the integer value
REM because we added 1 when we put it in the text box. This makes the actual
REM value correct again.

If Results=Int(Text1(SubCount).Text) - 1 Then

REM I added this so that you can actually see when the random number
REM that is generated has been found in a previous text box
REM remark this next line out if you do not want to see the results.

MsgBox Results + 1

REM The number had been used before if the code got here so we must generate
REM another random number to replace the one that we have.

Randomize Now()

REM See the notes above for the same code in the beginning of this sub.

Results = Int(Rnd * 52)

REM Same here.

Text1(SubCount).Text = Results + 1

REM This is the end of the second If Then statement.

End If

REM Check the loop count and drop out if it is done.

Next SubCount

REM End the first If Then statement.

End If

REM Check the loop count and drop out if it is done.

Next Count

End Sub

Some of the math and logic that is above may be confusing or difficult to understand, but it does work. If the math is confusing to you then I recommend that you study hard because much of programming uses this and much more difficult algorithms. We are not done yet. More code to write for the properties of the form, the command button and the label that we placed. For this, we go back to the Form Load sub-routine where we put the property settings for the text boxes. The following is the current code in the sub:

Private Sub Form_Load()

REM Declare the variable for counting our text boxes.

Dim Count As Integer

Rem Start counting from 0 because our array  index starts at 0.

For Count = 0 To 5

REM Set the text that is inside of the text box to nothing.

Text1(Count).Text = ""

Rem Set the text font that will be displayed in the textbox to the Tahoma font.

Text1(Count).Font = Tahoma

Rem Set the font property to bold.

Text1(Count).FontBold = True

Rem Set the size of the font to size 12

Text1(Count).FontSize = 12

Rem Align the text inside the box so that it appears in the center

Text1(Count).Alignment = 2

Rem This is where the program returns back up to the "FOR" part to see if it is
Rem finished counting. If it is, start the code immediately following this
Rem statement, which in this case is "End Sub".

Next Count

End Sub

We now need to set properties for the other controls. We place this code below the last "Next Count". Enter the following code to set these property values.

Command1.Font = Tahoma

Command1.FontSize = 16

Command1.FontBold = True

Command1.Caption = "LOTTO Bar"

Label1.Font = Tahoma

Label1.FontSize = 22

Label1.FontBold= True

Label1.Alignment = 2

Label1.BackColor= &H0000FFFF&

Label1.Caption = "Press the Big LOTTO Bar!"

Form1.BackColor = &H0000C000&

I will leave it up to you to figure out the meaning of these property settings. It should be clear by now.

When you are ready, press the F5 key on your keyboard and the program will run. If it doesnt run, something was copied wrong and you need to debug your project by carefully comparing your code to all of the code presented here. Spend some time examining the code and try to experiment with the code to change some property or add property values. The message box that pops up when a duplicate is found can be remarked out after you see what is going on when this occurs.

This is the end of our tutorial. Check again for more tutorials on my website.

A logo of Ardent Realty Group.

A picture of a young girl using an abacus.

A picture of a keypad key that says Help!