Anda di halaman 1dari 16

BITIC, Bahrain

The Programming Language


Components of Visual Basic Statements
Variables
Keywords (Reserved Words)
Constants
• Operators
• Built-in functions

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.

Rules for Naming Variable Names

The variable name must begin with a letter.


Name can contain letters, numeric digits or underscore.
Name can not include punctuation marks or other symbols except underscore.
Can have up to 255 characters.
Can not be restricted keyword or reserved word.

Valid Numeric Variable Names:


timeElapsed ; taxRate ; speed ;n ; Celsius ; file1 etc.

Invalid Variable Names:


maximum/average ; 1stChoice ; square yard ; while

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

B.Sc.(IT ) – Windows Programming in Visual Basic 1 Handout # 2


BITIC, Bahrain

•String – Alphanumeric data: letters, digits and other characters


•Date - An eight character date
•Object – Can be used to refer to any Excel object
•Variant - Converts from one type to another, as needed
Note : Please refer the text book for details.

Variant Data Type

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

Before using a variable, it should be declared using Dim statement.


The syntax for declaration of any variable is –

Dim < variable name > [ As < data type > ]

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

B.Sc.(IT ) – Windows Programming in Visual Basic 2 Handout # 2


BITIC, Bahrain

Dim amt As Double


Dim start_dt As Date

Default Values of any Variable

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.

Assigning Values to Variables


• The assignment statement can be used as follows to assign value to any variable.
• You cannot declare a variable and assign a value to it all in one statement. You
must put the assignment statement in a separate line.
• The syntax is –
variable name = expression
• Example –
name = “Visual Basic”
surname = “Abbas”
num1 = 32 + num2
a = b/c
x=y
c = 90
amt = 3.2223
start_dt = #16/4/2007#

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.

Example of use of String Variable


Private Sub cmdShow_Click()
picOutput.Cls
phrase = "win or lose that counts."
picOutput.Print "It's not whether you "; phrase
picOutput.Print "It's whether I "; phrase
End Sub

B.Sc.(IT ) – Windows Programming in Visual Basic 3 Handout # 2


BITIC, Bahrain

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.

A global variable can be used in all the procedures of a project. Module-level


variables are accessible from all procedures of a form. A local variable may be used
within the procedure in which it is declared.

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 >]

Here, the ‘Private’ keyword is optional i.e. not required.

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

Advantages of Local Variables


Extremely useful for team programming
To protect side effect (which is an accidental change of the value of the variable)
Example of Local Variables
Private Sub cmdButton_Click()
Dim var1 As Integer, var2 As Integer,num As Integer
var1 = 2
var2 = 4
Call Add(num)
Print num
End Sub
Private Sub Add(num As Integer)
Dim var1 As Integer, var2 As Integer
var1=1
var2=2
num = var1 + var2
End Sub
Module-level/Form-level variables
B.Sc.(IT ) – Windows Programming in Visual Basic 4 Handout # 2
BITIC, Bahrain

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.

A global variable can be declared as follows-

Public <variable name> [As Datatype]

And, a global constant can be declared as follows-

Public Const <constant name> [As DataType] = value

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-

Static <variable name> [As Data type]

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.

Eg. Label1.Caption =Text1.Text

Or

B.Sc.(IT ) – Windows Programming in Visual Basic 5 Handout # 2


BITIC, Bahrain

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

Valid Numeric Constants


Integer Real number
-2987 -1900.05
+16 0.0185
5 10.56

Invalid Numeric Constants


14,005.5 6.8%
33- $190.04
15 78 3.5&

Numeric Constants in a Statement:


tax = 0.02 * (income - 500 )
sum = 2 + x + 4.6 + y

String Constants
A group of alphanumeric data consisting of any type of symbols.

Valid String Constants


“A rose by any other name”
“Down By the Sea Shore”
“134.23”
“She said, ‘stop , thief!’”

Invalid String Constants


‘Down by the Seashore’
“134.24
“She said, “Stop, thief!”

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

B.Sc.(IT ) – Windows Programming in Visual Basic 6 Handout # 2


BITIC, Bahrain

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.

By declaring a constant, you can assign the number/value to a meaningful name in


one place in your program and then use that meaningful name elsewhere in your
program. Now, if you need to change this value, you just change at one place and
everywhere it’s used in your program will automatically use this new changed value.

Such a constant can be declared like –

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

Option Explicit Statement


The option explicit statement can be used to force explicit declaration of variables in
the program. Attempting to use an undeclared variable causes an error at compile
time.
Example-
Option Explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error

Also, the option explicit option can be set as follows-


1. From the Tools menu- select Options
2. On the Editor tab, make sure that Require Variable Declaration is selected.
3. Click the OK button.

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

B.Sc.(IT ) – Windows Programming in Visual Basic 8 Handout # 2


BITIC, Bahrain

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

When multiplication and division occur together in an expression, each operation is


evaluated as it occurs from left to right. When addition and subtraction occur together
in an expression, each operation is evaluated in order of appearance from left to right.
Parenthesis can be used to change the order of evaluation. Operations within
parentheses are always performed before those outside. Within parentheses, however,
operator precedence is maintained.
Examples
Evaluate the following expressions:
X=8/4/2
x = 3 * 6 - 12 / 3
x = 4 ^ (8 / 4)
y = 12 + 6 / (3 * (10 - 9))
z=5+4^2
m=6/3+3

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

B.Sc.(IT ) – Windows Programming in Visual Basic 9 Handout # 2


BITIC, Bahrain

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.

Visual Basic Print Method


Print: Print is a method used to display data on the screen.
It can be used to print value of variables.
It can be used to print value of arithmetic expressions.

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

Example of Print Method


Private Sub cmdCompute_Click()
Picture1.Print 3 - 2
Picture1.Print 3 * 2
Picture1.Print 3 / 2
Picture1.Print 3 ^ 2
Picture1.Print 2 * (3 + 4)
End Sub

Example of Print Method


x = 15
y=5
picOutput.Print (x + y) / 2, x / y
Output will be -

Example of Print Method


Sub Command1_Click()
Form1.Print “Hello World”

B.Sc.(IT ) – Windows Programming in Visual Basic 10 Handout # 2


BITIC, Bahrain

End Sub

Here, “Hello World” will be displayed on the form itself.

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

Using Text Boxes for Input/Output


By default, the text property of the text box holds string values.
The contents of a text box should be changed to a number before being assigned to a
numeric variable.

Example : Convert kilometers into centimeters and vice versa


Private Sub txtMeter_LostFocus()
txtcentm.Text = Str(Val(txtmeter.Text ) * 100)
End Sub
Private Sub txtCentm_LostFocus()
txtMeter.Text = Str(Val(txtCentm.Text) / 100)
End Sub

Example:Print the ASCII value for any pressed key. Write the code in
KeyPress Event Procedure

B.Sc.(IT ) – Windows Programming in Visual Basic 11 Handout # 2


BITIC, Bahrain

Private Sub text1_KeyPress(KeyAscii As Integer)


Text1.Text = ""
Picture1.Cls
Picture1.Print Chr(KeyAscii); " has ASCII value"; KeyAscii
End Sub
Note: Here KeyPress is an event for the text box which takes the ASCII value of the
pressed key as a parameter. The above code can be used to print the ASCII value of
any key that the user is pressing on the keyboard.

Standard Built-in Functions of VB


Types of Standard Functions
Numeric Functions (manipulate numbers)
String Functions (manipulate strings)

Numeric Functions
Common Examples:

Val(string) is a built-in VB function to convert any given string into a value.


Example-
Val (text1.Text) changes the input string into a number.
num = Val (text1.Text)

Rnd Function
Returns a random number from 0 up to 1 ( excluding 1).

Example: Displays a random integer from 1 through 6.


picBox.Print Int( 6 * Rnd) + 1

Sqr(number) Function
Returns the square root of a number.

Round(n,m)) Function
Round off the number n to m places.

Example for some commonly-used numeric functions


Private Sub cmdEvaluate_Click()
Dim n As Single, root As Single
picResults.Cls
n = 6.76
root = Sqr(n)
picResults.Print root; Int(n); Round(n,1)
End Sub

B.Sc.(IT ) – Windows Programming in Visual Basic 12 Handout # 2


BITIC, Bahrain

String Functions

Commonly-Used String Functions


Function: Left (“Penguin”,4) ‘Output is “Peng”
Purpose: Returns the number of specified characters, starting at the beginning of the
string.

Function: Right (“Gotham City”, 4) ‘Output is “tham”


Purpose: Returns the number of specified characters from the end of the string.

Function: Mid (“Commissioner”, 4, 3) ‘Output is “mis”


Purpose: Returns the character string starting at the position indicated by the first
number and continuing for the length specified by the second number.

Function: UCase ( “Yes”) ‘Output is “YES”


Purpose: Converts any lowercase letters in string to uppercase.

Function: LCase ( “Yes”) ‘Outputis “yes”


Purpose: Converts any uppercase letters in string to lowercase.

Function: InStr (“John Smith”, ” “) ‘Output is 5


Purpose: Searches for the first occurrence of one string in another and gives the
position at which the string is found.

String-Related Numeric Function

Function: Len (“John Smith”)


Purpose: Returns the number of characters in the string.

Function: Chr(Ascii Value)


Purpose: Converts the ASCII value into its corresponding character.

Changing Multiple Properties of a Control- With Statement

Sometimes, we want to change the multiple properties of a control, then the ‘With’
statement can be used.

B.Sc.(IT ) – Windows Programming in Visual Basic 13 Handout # 2


BITIC, Bahrain

Syntax of ‘With’ statement is as follows-

With <control name>


Statement(s)
End With

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.

Setting a Border And Style


Most controls can appear to be three dimensional or flat. Labels, text boxes, option
buttons and images all have an Appearance property, with choices of 0 – Flat, or 1 –
3D. To make a label or an image appear 3D, you must first give it a border. Set the
Borderstyle to 1 – Fixed Single. The Appearance property defaults to 1 – 3D.

Defining Keyboard Access Keys


The keyboard can be used to select the options on the interface by pressing the Alt
key and the hot key. The access keys can be set for command buttons, option buttons
and check boxes in their ‘Caption’ property. Type an & in front of the character you
want for the access key. VB will underline that character.

---***---

What have we learnt?

1. Which different component windows are present on the Visual Basic desktop?

B.Sc.(IT ) – Windows Programming in Visual Basic 14 Handout # 2


BITIC, Bahrain

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

Private Sub txtMt_Change()


Dim m As Single
m = Val(txtCm.Text)
txtCm = m * 100
End Sub
21. Write a program which displays the ASCII value of any key (printable) pressed by
the user.
Solution:
Private Sub text1_KeyPress(KeyAscii As Integer)
Text1.Text = ""
Picture1.Cls
Picture1.Print Chr(KeyAscii); " has ANSI value"; KeyAscii
End Sub

-----***-----

B.Sc.(IT ) – Windows Programming in Visual Basic 16 Handout # 2

Anda mungkin juga menyukai