Lesson 6: Working with Variables

6.1 Assigning Values to Variables


After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is


The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more. The following are some examples:


userName=”John Lyan”
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber  


6.2 Operators in Visual Basic

To compute inputs from users and to generate results, we need to use various mathematical operators. In Visual Basic, except for + and -, the symbols for the operators are different from normal mathematical operators, as shown in Table 6.1.

Table 6.1: Arithmetic Operators


Mathematical function Example


Exponential 2^4=16


Multiplication 4*3=12,  


Division 12/4=3


Modulus (returns the remainder from an integer division) 15 Mod 4=3   


Integer Division(discards the decimal places) 19\4=4

+ or &

String concatenation “Visual”&”Basic”=”Visual Basic”



Example 6.1


Dim firstName As String

Dim secondName As String

Dim yourName As String


 Private Sub Command1_Click()

firstName = Text1.Text

secondName = Text2.Text

yourName = secondName + ”  ” + firstName

          Label1.Caption = yourName

End Sub

In this example, three variables are declared as string. For variables firstName and secondName will receive their data from the user’s input into textbox1 and textbox2, and the variable yourName will be assigned the data by combining the first two variables.  Finally, yourName is displayed on Label1.


Example 6.2


Dim number1, number2, number3 as Integer

Dim total, average as variant

Private sub Form_Click

number3= val(Text3.Text)





End Sub


In the example above, three variables are declared as integer and two variables are declared as variant. Variant means the variable can hold any data type. The program computes the total and average of the three numbers that are entered into three text boxes.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s