Variables

A variable is a named location in memory where you can store values. In the previous lesson you wrote a program to display a random color every time you clicked, but you did not know what the color was. Variables would let us assign a random value to a variable named Red for example and then use the stored value to change the color. Because the value of a variable is stored in memory, we can also display the value in the text.

Variable Names must start with a letter of the alphabet: after the first letter, it can have more letters, digits, and underscores. Blanks are not allowed. Two words can be separated by an underscore, or the second word can begin with a capital letter to make it readable: HoursWorked or Hourly_rate, for example. You can not use keywords such as end, if or sub that have a special meaning in Visual Basic.

Type: Each variable also has a type. There are hundred of types, but we usually use one of the following:
Integer: whole numbers with no decimal places;
Double: numbers with decimal places;
String: for names, words, etc.
Boolean: for variables that can be either True or False.

Close any open project and start a new windows application called Colors.

In the last lesson, we had a fairly long statement to select a random color. In this program we will use variables to store the values of red, green, and blue. Then we can use those values to change the color of the background and also to display the values of the new color. Write the code as shown below:

Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
     Handles Me.MouseClick
  Dim Red, Green, Blue As Integer
  Red = Rnd() * 255
  Green = Rnd() * 255
  Blue = Rnd() * 255
  Me.BackColor = Color.FromArgb(Red, Green, Blue)
  Me.Text = Hex(Red) & Hex(Green) & Hex(Blue) 'shows the hex value of the color
End Sub 'Form1_MouseClick

colors


INDEX, Introduction to Variables, Assigning Values to a Variable, Short Cut Notations, Global variables
Next lesson: Boolean Expressions in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Introduction to Variables