Variables
A variable is a storage location in computer’s main memory where data is stored. The
contents or value of a variable can be changed during program execution but its
name and storage are reserved for use until you end the program.
It is a placeholder in memory for an unknown value.
Every variable has three properties: a Name, a Value, and a Data Type.
Before using any variable, it has to be declared using DIM statement.
Data Types
The data type determines what type of values may be stored in a variable or constant.
VB recognizes the following data types:
• Integer – Whole numbers in the range -32,768 to 32,767
• Long - Large whole numbers
• Single - Single precision floating point numbers with 6 digits of accuracy
• Double - Double precision floating point numbers with 14 digits of accuracy
• Boolean – True or False
• Currency – Useful for fixed point calculations where accuracy is important
The default data type is ‘Variant’. If you do not specify a data type, your variables
and constants will be of data type variants.
The variant data type allows you to store any type of data in a variable. This variable
can also change its type at any time. So, it is a flexible data type. At one point, it may
take in a String value, but later can store a number.
Example –
Dim vnt As Variant
vnt = 10
……
vnt = 5.5
…..
vnt = “Hi!”
The advantage of using variant data type is that it’s easy and the variables and
constants change their appearance as needed for each situation. The disadvantage is
that variants are less efficient than the other data types; that is, variants require more
memory and operate less quickly than other data types. The best practice is to always
specify the data type.
Declaration of Variables
These [ ] means that this portion of the syntax is optional, not compulsory.
If we do not specify any data type for a variable in VB, it is assumed to be of Variant
data type. Variant is the default data type for any undeclared variables.
Example –
Dim num1 As Integer
Dim name As String
Dim num1, num2 As Integer ‘(Here num1 will have data type as Variant)
Dim x As Integer, y As Integer
When you declare variables, VB gives each variable a default value. This value will
be different for the different data types.
For numeric data types, it will always be 0 (zero). For a string variable, it will be a
blank string (””)
Note: Always use Val function to convert text values to numeric before performing
any calculations.
Note: The symbol # called as pound sign tells VB to treat the numbers as date
instead of some mathematical expression to be solved. The format of the date to be
displayed in the program depends on the current date settings within the Windows
OS.
Scope of Variables
A variable may exist and be visible for an entire project, for only one form, or for
only one procedure. The availability of a variable is referred to as its scope. The
scope can be global, module-level or local.
Local/Private Variables
Any variable that is declared inside any sub procedure or function is local in scope; it
is known only to that procedure or function. They are declared using DIM statement
as follows:
[Private] Dim < variable name > [ As < data type >]
Once the procedure is finished, these local variables and constants are also lost.
Variables in different procedures are totally independent. Different procedures can
have variables with the same names; however, each variable will have its own
memory location
At times we want to use a particular variable in more than one procedure of a form,
then module level variables can be used. The module level variables and constants
can be declared in the ‘General Declarations’ section of the form. To display the
General Declarations section, first go to code window; then in the Object list, select
(General); in the Procedure list, select (Declarations). These variables can be used in
all the procedures within that form.
Global/Public Variables
If a variable or a constant has to be used in more than one form in the project, then it
must be declared as a global variable.
Static variables
Static variables retain their value for the life of the project rather than being
reinitialized for each call to the procedure.
Example, to find the running total, it can be declared as a static variable inside a
procedure or function.
Syntax is-
The Static statements can appear only in procedures and can never appear in the
General Declarations of a module.
Controls as Variables
The values stored in controls can be used in the program code and thus the controls
can be used as variables.
Or
Label1 = Text1
would copy whatever was in the text box into the label.
Constant
Constants are used to store a value that doesn’t change. A constant has also to be
declared as similar to a variable, but its value can not be changed throughout the life
of your program.
Types of Constants-
Numeric Constants
String Constants
String Constants
A group of alphanumeric data consisting of any type of symbols.
There are two main advantages of using named constants rather than the actual values
in code. The code is easier to read; for example, seeing the identifier MaximumPay is
more meaningful than seeing a number, such as 10000. In addition, when a particular
constant value is used in several locations throughout our program and if you need to
change the value at a later time, you need to change the constant declaration only
once and not change every reference to it throughout the code manually.
Const < constant name > As < data type > = <value>
Examples –
Const conHello As String = “Hello Visual Basic Programmers”
Const Pi As Single = 3.14
Const errmsg As String = “Incorrect Input”
Usage –
Sub Command1_click()
Const conHello As String = “Hello Visual Basic Programmers”
………….
Label1.Caption = conHello
…………..
End Sub
When you turn on the Require Variable Declaration option, VB automatically adds
the Option Explicit statements to all the new forms you create after that point
Operators
B.Sc.(IT ) – Windows Programming in Visual Basic 7 Handout # 2
BITIC, Bahrain
Operators Description
Arithmetic Operators Operators used to perform mathematical calculations.
Comparison Operators Operators used to perform comparisons.
Concatenation Operators Operators used to combine strings.
Logical Operators Operators used to perform logical operations.
Arithmetic Operators
Operator Operation Basic expression Example
^ Exponentiation A^B 4 ^ 2 = 16
* Multiplication A*B 4*2=8
/ Division A/B 4/3 = 1.33
+ Addition A+B 4+2=6
- Subtraction A–B 4–2=2
\ Integer Division A\B 4\3 =1
MOD Remainder A mod B 4 Mod 3 = 1
Note:
Integer Division (\) divides one number by another number but truncates the decimal
portion of the number.
Mod Operator
Used to divide two numbers and return only the remainder.
Example-
10 Mod 5 ' Returns 0.
10 Mod 3 ' Returns 1.
Comparison Operators
= <> < > >= <= Like Is
Logical Operators
AND OR NOT
Concatenation Operators
& Operator + Operator
Operator Precedence
The order in which operations are performed determines the result. When several
operators occur together in an expression, each part is evaluated in a predetermined
order called as operator precedence.
When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and logical
operators are evaluated last.
Comparison operators all have equal precedence; that is, they are evaluated in the
left-to-right order in which they appear. The order of precedence for logical operators
is – NOT, AND and then OR.
The hierarchy of operations in arithmetic expressions from highest to lowest is as
follows-
1. Exponentiation
2. Multiplication and division
3. Addition and subtraction
Reserved Words/Keywords
Words that have predefined meaning to Visual Basic are known as keywords or
reserved words.
They can not be used as variable names.
Example: Print ; Cls ; If ; While
Internal Documentation
An apostrophe (‘) can be used to indicate comments; comments are ignored by Visual
Basic.
The keyword Rem can also be used instead of an apostrophe for comments.
Remarks can also be placed after program statement too.
End Statement
The End statement stops the execution of a project. It can be used in the sub
procedure for an Exit button or an Exit menu choice.
Note: Methods are in-built code routines hidden inside the control. Like statements
in other languages, they perform actions. But each control has a different set of
methods that can be used with it.
For example –
o List Box has methods like AddItem, RemoveItem etc.
o Form has Print method
o Picture Box has Print method, Cls method
End Sub
Concatenation Operator
Two strings can be combined with the concatenation operator.
Concatenation operator is represented with the ampersand ( & ) sign.
Example of Concatenation:
str1 = “Hello”
str2 = “World”
picOutput.Print str1& str2
Output is – “HelloWorld”
Example of Concatenation
txtBox.Text = “32” & Chr(176) & “ Fahrenheit”
Output is - 32°Fahrnheit
Example:Print the ASCII value for any pressed key. Write the code in
KeyPress Event Procedure
Numeric Functions
Common Examples:
Rnd Function
Returns a random number from 0 up to 1 ( excluding 1).
Sqr(number) Function
Returns the square root of a number.
Round(n,m)) Function
Round off the number n to m places.
String Functions
Sometimes, we want to change the multiple properties of a control, then the ‘With’
statement can be used.
Example,
With txtTitle
.Visible = True
.Forecolor = vbWhite
.Font.Bold = True
.Font.Italic = True
.SetFocus
End With
The real advantage is that the ‘With’ statement is more efficient. The VB project will
run a little faster , if you use With.
---***---
1. Which different component windows are present on the Visual Basic desktop?
2. What are variables? How any variable is declared in Visual Basic? Give some
examples
3. List the different data types present in Visual Basic.
4. Define Variant data type available in Visual basic. Give one example to support your
answer.
5. How the controls are used as variables in VB? Give example.
6. Describe local, global, module-level and static variables.
7. Define static variables? Give example.
8. What are constants? Which are the two different types of constants in VB? Give
example for each type.
9. What is the main advantage of using a constant in a program?
10. How a constant can be declared in a VB program? Give examples for declaring a
constant.
11. List the different arithmetic operators in VB with one example for each.
12. Write a short note on ‘Operator Precedence’.
13. Explain the usage of ‘With’ statement.
14. Explain the use of ‘Option Explicit’ statement.
15. What is the function of concatenation in VB? Give example.
16. Explain-
a) Val function
b) SetFocus method
17. Write a program to convert a given quantity in kilograms to pounds, using the
formula-
1 Kilogram = 2.2 pounds
Write a VB program to enter two numbers in two text boxes and find their product.
18. Write the code that multiplies the two entered numbers in the text boxes and display
the result on pressing the ‘Enter key’ after the second number.
Private Sub Text2_KeyPress(KeyAscii As Integer)
Dim num1 As Integer, num2 As Integer
If KeyAscii = 13 Then
num1 = Text1.Text
num2 = Text2.Text
MsgBox "Result is " & Str(num1 + num2)
End If
End Sub
19. Write a program that accepts a character. If the character is a lowercase letter,
convert the letter to uppercase and display the letter in its uppercase form.
20. Write a program to convert centimeters into meters and vice-versa using the formula-
1 meter = 100 cm
B.Sc.(IT ) – Windows Programming in Visual Basic 15 Handout # 2
BITIC, Bahrain
Hint: Use Text boxes to take the input in meter and centimeter. The conversion code
can be attached to the ‘Change’ event of the text boxes.
Solution:
Private Sub txtCm_Change()
Dim cm As Single
cm = Val(txtCm.Text)
txtMt = cm / 100
End Sub
-----***-----