Sunteți pe pagina 1din 35

Writing Simple Codes

At the end of this unit, the student will be able to:

 Write simple codes in Visual Basic


 Understand levels of scope in Visual Basic
 Convert basic knowledge about variables, constant and operators
in VB programming
 Maximize the use VB functions
 Apply basic knowledge in conditional and looping statements in
VB programming.

2 VISUAL BASIC: An Approach to Program Development


LESSON

9 USING VARIABLES AND CONSTANTS

OBJECTIVES  Enumerate pointers in proper coding


 Observe proper way of coding programs
 Analyze the use of the different scope levels of VB
programming
 Identify types and scopes of variable
 Create simple code using variables and constant.

Writing Easy and Simple Codes

There are some pointers that should be followed in writing codes.

- Descriptive Naming
Exercise using descriptive names in all controls and variables. This will avoid
confusion and makes programming hassle – free. This one of the rules in
Naming conventions especially for variables.

- Indentation
Indentation is used especially in control structures (conditional
statements). It makes the follow of logic easier for variables.

- Comments
Comments amend source code to make it more understandable. They serve
as inline documentation that helps to read, reuse, understand and maintain
existing code. The alternatives for commenting are self – documenting code
and separate code documents. In reality, few pieces of code are entirely
self – documenting. Separate code documents, are often incomplete. What
is more, they go out of date easily as the code gets modifies. On the

3 VISUAL BASIC: An Approach to Program Development


contrary, comments are there are read and update when the code is
worked on.

- Capitalization
In Visual Basic, always use capital letters in the beginning of keywords.

- Continuation Character
If you have a long statements, write them in 2 lines using the continuation
character, space underscore (_). When encountering an error in putting 1
statements in 2 lines without putting the continuation character, it is
because Visual Basic reads every line as individual statements.

- Use of Suggestion Lists Box inside the Code Editor


Click on the options in the drop down list box that appears when typing
codes.

4 VISUAL BASIC: An Approach to Program Development


- Be very ardent to details
A common mistake in programming is typographical error. Bear in mind
that a single incorrect spelling will produce an error in the code.

Levels of Scope in Visual Basic

Variables and constants can be use d or can be called upon at certain ranges
depending on their placement in the program. They

1. Block Level Scope

When a variable or constant is declared in a distinct code structure (such as


and if statement or Do loop), the variable is only visible and accessible to
the code within that structure. For example, in the following code the
intCustCount variable is only accessible to code within the If statement:

2. Procedure Level Scope

Variables and constants declared within a Visual Basic procedure (i.e. a


Function of Subroutine) are only visible and accessible to code within that
procedure (for details of Visual Basic procedures see Visual Basic Modules
and Procedures) For example, the variable intResult in the following code is
only visible to code within the function:

5 VISUAL BASIC: An Approach to Program Development


3. Module Level Scope

When a variable or constant is declared outside of any procedures or code


structures in a Module it is deemed to have module level space. This means
that the variable or constant is visible to all Visual Basic code contained in
the same module, regardless of whether that code is located in a procedure
or not. There is a section at the top of each module called the Declarations
Section for this purpose. The Declaration section is located above all
procedures and code in a module.

4. Global Scope

When a variables or constant is declared as global it is visible to all


procedures and modules that comprise the application. Global variables
and constants, as with Module level variables, must be declared outside of
any procedures in the Declarations selection and must use the Public
keyword. The syntax for declaring a global variable is as follows:

Similarly, a global constant is defined using the following syntax.

Working with Variables

Variables are designed to hold different values, but not at the same time.
Variables are dynamic. You set them, you change them, you display them and you
unload them.
All variables must be named in the code. Two different variables cannot have the
same name within one procedure. Unlike controls where VB gives them a default
name when they are placed on a form, variables do not have names until you
name them. Before a variable can be used, you must declare the variable by
telling VB the name and data type the variable is to hold. Variables can only hold
data from their declared type. The only exception is the variant data type.

6 VISUAL BASIC: An Approach to Program Development


Scope of Variables

Variables may have two different kinds of “lifetimes”, or scopes. If you


declare a variable outside of any function declaration, it is a global variable.
If you declare it inside a function declaration, it is a local variable.

1. Local variables

A local variable only exist while the function it is local to (the one you
declared it in) is executing. It vanishes when the function returns, and
reappears (with some different value) when the function executes later. If
you call the function recursively, each call of the function has its own value
for the local variable. You may also declare a variable to be local to a block,
in which case it exist only when code inside the block is executing. A local
variable so declared only has meaning inside the function or block it is local
to. This can be done using Private Statement in which variable can be only
be used in form where it is declared.

Two Levels of Local variables:

a. Module – level - variables in the declaration selection of the module,


is only available for the control.

b. Procedure – level – variables declared inside a procedure. It is only


available when the procedure is called. It will go back to is original value
once it is called.

2. Global Variables

A global variable exists independently of any function. Any function may use
it. It functions declared in different source files use the same global variable,
the variable must be declared in both source files (or in files # included by
both files) before its first use. If the two files have different initializations for
the variable, only the first initialization has an effect.

If a global variable has the same name as a global variable, the local masks the
global variable. All references in the block to a variable of that name, from the
local variable’s definition until the end of the block it is defined in, are to the

7 VISUAL BASIC: An Approach to Program Development


local variable. After the end of the block, the name again refers to the global
variable. This can be done using Public Statements where in variable can be
used in different forms inside the project.

Analyzing the Scope of a Variable

Normally a variable in scope or visible for references, throughout the region in which
it was declared. In some cases, the variable’s access level can influences its scope.

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;

Variable = Expression

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) etc. The following are some examples:

8 VISUAL BASIC: An Approach to Program Development


Declaring Variable

In Visual basic, one needs to declare the variables before using them by assigning
names and data types. They are normally declared in the general section of the
code’s windows using the Dim statement

1. Implicit Declaration – Variable is not formally declared. It is a result of


other variable declarations.

9 VISUAL BASIC: An Approach to Program Development


You may also combine them in one line, separating each variable with a comma 9,)
as follows:

2. Explicit Declaration – variable is declared at the beginning of the


procedure in the Declaration Section.

If the data type is not specified, VBB will automatically declare the variable as a
Variant. For string declaration, there are two possible formats, one for the variable
length string and another for the fixed – length string.

Working with Constants

Constant are named storage locations in memory, the value of which that does not
change during program Execution. The Const statement is used to create a constant.
Constant can be declared in local, form, module or global scope and can be public or
private as for variables.

10 VISUAL BASIC: An Approach to Program Development


A constant statement can represent a mathematical or date/time quantity:

It can also define String constant:

The expression on the right side of the equal sign (=) is often a number of literal
string, but it also can be an expression that results in a number or string (although
that expression cannot contain calls to functions). You can even define constant in
terms of previously defined constants:

Two Types of Constants

1. Intrinsic Constant

Constant store values that remains constant throughout the execution of an


application. They are meaningful names that take the place of a number or
string and make code more readable. Enumerations after an easy way to work
with sets of related constants. An enumeration, or Enum, is a symbolic name
for a set of values. You can create your own constants and enumerations or
you can sue the intrinsic constants and enumerations Visual Basic provides,
which are listed in the Object Browser.

The following table lists and describes the intrinsic enumerations available in
Visual Basic.

11 VISUAL BASIC: An Approach to Program Development


11 VISUAL BASIC: An Approach to Program Development
2. User – Defined Constant

A constant is a meaningful name that takes place of a number or string that


does not change. Constants store values that, as the name implies, remain
constant throughout the execution of an application. You can use constant
that are defined by the controls or components you work with, or you can
create your own. Constant you create are described as used – defined

You declare a constant with the Const statement, using the same guidelines
you would for creating a variable name. If option Strict is On, you must
explicitly declare the constant type.

Understanding Variable and Constant Scope

Variables and constant can be declared anywhere in a Visual Basic project. It is


important to understand how the variable is declared and dictates the scope of that
variable. The scope of a variable relates to where else in the application source code
the variable is accessible.

12 VISUAL BASIC: An Approach to Program Development


LESSON
USING OPERATIONS AND FUNCTIONS
10

OBJECTIVES  Review the different mathematical operators


 Use mathematical operators in programming
 Identify VB program function
 Distinguish different types of program functions
 Apply functions in programming

Working with Operators

The different operators were already tackled in the previous unit of this book.
There are 3 types of mathematical operators namely: mathematical and text
operators, relational and logical

Mathematical Operators: REVIEW

Arithmetic operators involve the common math problems that compute from
single to complex: These include addition (+)r, subtraction (-), multiplication (*),
division (/) and the modulus division (%).

Relational operators show equalities and inequalities of mathematical


relationships. These include equal (=), not equal (!=), less than (<), greater than
(>), less than or equal (<=) and greater than or equal (>=).

Logical operators solve Boolean math and usually found in compound conditions.
Thought there are 8, the commonly used are AND (&&), OR (II) and NOT (!)

In order to compute inputs from users and to generate results, there is a need to
use various mathematical operators. In Visual Basic, except for + and -, the
symbols for the operators are different from normal mathematical operators.

13 VISUAL BASIC: An Approach to Program Development


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

In this example, 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.

Functions

Functions are similar to normal procedures but the main purpose of the functions
is to accept certain inputs and pass them on to the main program to finish the

14 VISUAL BASIC: An Approach to Program Development


execution. These are the two types of function, the built – in functions (or internal
functions) and the functions created by the programmers.

The general format of a function is;

Where arguments are values that are passed on to the functions.

String Functions

Please take not that Strings are not objects so they do not have methods but
there is a number of functions that manipulate strings

15 VISUAL BASIC: An Approach to Program Development


Date Functions

The Date function reads the system clock and returns the current date as a string
in the format: MM/DD/YY (that is, the string returned contains two digit numerals
each for month, day and year, separated by slash marks).

Function Description Result


Now Returns both the current Now ()
date and time from the
system clock
Example: 03/16/2010 6:30:23 PM
Lbl.Caption=Now ()
Date Returns the current date Result:
of the computer being 03/16/2010
used
Example: Result:
Dim Cur_Time as String 2:08:34 Pm
Cur Time = Time
Format Returns a formatted string Format(string, “specified
according to user defined format”)
format
Example: 2006 – 10- 16
Dim Cur_Date as Date
Lbll.caption = Format (Cur_Date, “yyy-mm-dd”)

Formatting Characters for Date

Formatting Description Example Formatting Description Example


Characters Characters
Year Day of the
yy without 06 dd month with 09
century zero
Year with Name of
yyy century 2015 dddd the day of Friday
the week
m Number of 11 h Hour 8

16 VISUAL BASIC: An Approach to Program Development


month without
zero

Number Functions

Unlike the date function, number function only reads numbers that are
computable

Returns a formatted Format(string, “specified


Format string according to used format”)
defined format
Example:
Dim Result as Single
Result = 245.6 245.60
Lbl.caption=Format (Result, “0000.00”) $245.60
Lbl.caption=Format (Result, “$00.00”)

Formatting Characters for Numbers

Formatting characters Description


0 Represents a digit, with non –
significant leading and trailing zeros
# Represents a digit, without non –
significant leading and trailing zeros
. Decimal placeholder
, Thousands separator
$+-() space Literal character; displayed as typed

Input/Output Functions

Input/Output Functions allow the system to handle input from the user and
output that is resulted from the code.

inputBox Display a dialog box with


a prompt and textbox InputBox (“prompt”)
with the OK and CANCEL
button

17 VISUAL BASIC: An Approach to Program Development


Example:
InputBox (“Type your name:”)

Display a pop – up box


MsgBox with a message and MsgBox (“prompt”)
waits the user to click
and button.
Example:
MsgBox (“Welcome to
Visual Basic!!!”)

InputBox ( ) Function

This displays a message box where user can input data.

Syntax:

Variable=InputBox (Prompt, Title, default_text, x – position, y – position)

 Prompt – the message displayed prompting what is to be entered


 Title – the title of the input Box
 Default – text – the default text that appears inside the input box.
 X – position and y – position – the position or the coordinates of the input
box.

18 VISUAL BASIC: An Approach to Program Development


Example:

MsgBox ( ) Function

This produces a pop – up message ox and prompts the user to click on a


command button before going to the next instruction.

19 VISUAL BASIC: An Approach to Program Development


Syntax:
Variable=MsgBox (Prompt, Style Value, Title)

 Prompt – the message displayed in the message box


 Style value – The type of a command button/s that will appear on the
message box
 Title – title of the Message box.
 X – position and y – position – he position or the coordinates of the input
box.

Sky Values

Style Value Named Constant Displayed Button/s


0 vboKonly Ok Button
1 vbokCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry, and Ignore
buttons
3 vbNoCancel Yes, No and Cancel
Buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

The variable holds values that are returned by the MsgBox ( ) function. The values
are determined by the type of buttons being clicked by the user. It has to be
declared as integer data type in the procedure or in the general declaration
section.

Return Values and Command Buttons

Value Named Constant Clicked button


1 vbok Ok button
2 vbokCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button

20 VISUAL BASIC: An Approach to Program Development


Icons

Value Named Constant Icon


16 vbCritical X
32 vbQuestion ?

21 VISUAL BASIC: An Approach to Program Development


48 vbExclamation !
64 vbInformation i

22 VISUAL BASIC: An Approach to Program Development


LESSON
USING CONDITIONAL & LOOPING STATEMENTS
11

OBJECTIVES  Analyze how to incorporate decision in the program


 Define when to use the different types of conditional and loop
statements
 Follow the correct syntax for every type of conditional and
loop statements
 Write simple code using conditional and loop statements.

Working with Conditional Statements

If…Then Structure

In Visual Basic, you can write an “If…Then” statement for handling True
conditions in two ways: the “single – line If…Then” statement and the “multi –
line If…Then statement”. Each uses the If..Then keywords to check a condition. If
the condition is True, the program runs the commands associated with the
If…Then statement. If the condition is False, the commands are skipped or ended.

If…Then selection structure performs an indicated action only when the condition
is true; otherwise the action is skipped.

Review Syntax:

If <condition> Then
Statement
End If

The conditional statement is an expression that returns a true of false result. The
conditional statement may be a Boolean value or a longer expression that
includes conditional and possibly one or more logical operators.
Private Sub andCompare_Click ()
If (txtSales > txtTotal) Then ‘sales is greater than total
txtSales.Backcolor = vbGreen
End If
End Sub

23 VISUAL BASIC: An Approach to Program Development


Here is the runtime application for the code above.
The form appears on the screen with two text boxes waiting for input.

The user enters values into the text box and clicks the compare button.

According to the code above, if the scales exceed the total, then the background
color for the scales text box will turn green. In this example, the sales clearly
exceed the total and the backcolor turns green.

24 VISUAL BASIC: An Approach to Program Development


If…Then…Else Structure

Then If…Then..Else selection structure allows the programmer to specify that a


different action is to be performed when the condition is True than when the
condition is False.

Review Syntax:

If <condition> Then
Statement
Else
Statements
End If

25 VISUAL BASIC: An Approach to Program Development


The if and End If statements of this block are the same as before. The condition is
still any logical expression or variable that yields a True or False value. The key
element in this set of statements is the Else statement. This statement is placed
after the last statement to be executed if the condition is True, and before the
first statement to be executed if the condition is False, For a True condition, the
program processes the statements up to the Else statement and then skips to the
first statement after the End If. If the condition is False, the program skips the
statements before the Else statement and starts processing with the first
statement after the Else.

If executing a code for only the False portion of the statement, place code
statements between the Else and End if statements; placing any statements
between the If and Else statements are not required.

If x <= 1 then
Else
MsgBox “X is not greater than 1”
End If

Nested If Structure

If the test is needed for a condition that depends on whether another condition is
already True (such as “If statement” is one that’s enclosed within another “If
statement”. Nested If…Then…Else selection structures test for multiple cases by
placing If…Then…Else selection structures inside If…Then…Else structures. You can
use Nested If either of the methods as shown below:

Review Syntax:

If <condition1> Then
Statements
Elself <condition2> Then
Statements
Elself <condition3> Then
Statements

Else ‘Elself is also acceptable given another condition
End If

26 VISUAL BASIC: An Approach to Program Development


Or this Syntax:

If <condition1> Then
Statements
Elself <condition2> Then
Statements
Elself <condition3> Then
Statements
Else
Statements
End If
End If
End If

The following code snippet demonstrates a nested If statement:

If optDivision.Value = True Then


If y < > 0 Then
Z=x/y
Else
‘Report an error
MsgBox “Cannot divide by zero”, vbCritical,
“Error”
End If
End If

Example 1:
Assume you have to find the grade using nested if and display in a text box.

If optDivision.Value = True Then


If y < > 0 Then
Z=x/y
Else
‘Report an error
MsgBox “Cannot divide by zero”, vbCritical,
“Error”
End If
End If

27 VISUAL BASIC: An Approach to Program Development


Example 2:

Private Sub cmdCompute_Click ( )


If (txtAverage >= 80) Then ‘test if absences is less than or equal to 80%
lblGrantedII.Caption = “Yes” ‘all conditions are met
Else
lblGrantedII.Caption = “No” ‘too many absences
End If
Else
lblGrantedII.caption = “no” ‘average is not over 80%
End If
End sub

Here is the code in action.


In this window, the student meets both criteria to quality for an exemption.

In this window, the student has a high enough average for an exemption, but has
one too may absences

28 VISUAL BASIC: An Approach to Program Development


In this window, the student has no absences, but is one mark short of quality for
an exemption.

Select Case Structure

Select…case structure is an alternative to If…Then….Else If for selectively


executing a single block of statements from among multiple blocks of statements.
Select…case is more convenient to use than the If…Else…End If. The following
program blocks illustrate the working of Select ….Case.

Review Syntax:

Select Case Index


Case 0
Statements
Case 1
Statements ‘Case Else is also acceptable as last
Option

End Select

29 VISUAL BASIC: An Approach to Program Development


Example 1:
Assume you have to find the grade using Select Case and display it in the text box.

Dim average as Integer


Average = txtAverage.Text

Select Case average

Case 100 To 75
txtGrade.Text = “A”
Case 74 To 65
txtGrade.Text = “B”
Case 64 To 55
txtGrade.Text = “C”
Case 54 To 45
txtGrade.Text = “S”
Case 44 To 0
txtGrade.Text = “F”
Case Else
MsgBox “Invalid average marks”
End Select

Working with Looping Statements

Do…While Structure

Do…While loop consists of block of code and a condition. First, the code within
the block is executed, and then the condition is evaluated. If the condition is true
the code within the block is executed again. In example, the statement repeats
until the condition becomes false. The following Do Loop counts from 1 to 100.

Dim number AS Integer


Number = 1

Do While number <=100


Number = number + 1
Loop

30 VISUAL BASIC: An Approach to Program Development


A variable number is initialized to 1 and then the Do While Loop starts. First, the
condition is tested; if the condition is true, then the statements are executed.
When it gets to the Loop it goes back to the Do and tests condition again. If the
condition is False on the first pass, the statements are never executed.

Review Syntax:

Do While condition
Statement (s)
Loop

OR

Do
Statements/s
Loop While
Condition

Example 1: Example 2:

Dim Numbers as Integer Dim Numl as Integer


Number = 20 Numl = 10
Do While Number < 30 Do
Number = Number + 2 Numl = Numl + 2
Print Number Print Numl
Loop Loop While Numl

A variable number is initialized to 1 and then the Do While Loop starts. First, the
condition is tested; if the condition is True, then the statements are executed.
When it gets to the Loop it goes back to the Do and tests condition again. If
condition is False on the first pass, the statements are never executed.

Do…Until Structure

The Do…Until Loop is a loop that constructs similar to the while loop, but runts at
least once. The syntax of the do…until loop is exactly what you would expect from
its name. note that Unreal Script doesn’t “do..while”, that means it loops until the

31 VISUAL BASIC: An Approach to Program Development


condition is True. (or while it is False) Like in any other loop construct you can use
break and continue to exit the loop or jump to the next iteration.

Review Syntax:

Do Until condition
Statement (s)
Loop

OR

Do
Statements
Loop Until
condition

Example:

Dim number As Long


Number = 0

Do Until number > 1000


Number = number + 1
Print Number
Loop

Numbers between 1 to 1000 will be displayed on the form as soon as you click on
the command button.

For…Next Structure

The For…Next loop is another way to make loops in Visual basic. For…Next
repetition structure handles all the details of counter – controlled repetition. The
following loop counts the numbers from 1 to 100:

Review Syntax:

For counter = start to end (Step Increment)


Statements (s)
Next counter

32 VISUAL BASIC: An Approach to Program Development


OR

For counter = start to end (Step Increment)


Statements
Next

Example 1:

Dim x As Integer
For x = 1 To 50
Print x
Next

In order to count the numbers from 1 to 50 steps of 2, the following loop can be
used.

For x = 1 To 50 Step 2
Print x
Next

The following loop counts numbers as 1, 3, 7…,etc. The above coding will display
numbers vertically on the form. In order to display numbers horizontally the
following method can be used:
For x = 1 To 50
Print x & Space $ (2);
Next

To increase the space between the numbers increase the value inside the
brackets after the & space $

Example 2:
Following example is a For…Next repetition structure which is with the If
condition used.

33 VISUAL BASIC: An Approach to Program Development


Dim number AS Integer

For number = 1 To 10
If number = 4 Then
Print “This is number 4”
Else
Print number
End If
Next

In the output instead of number 4 you will get the “This is number 4”.

Understanding Conditional and Loop Statements

In an effort to make the codes sleek and elegant, conditions are often combined
into a single statement with the help of a logical operator, as in:

If X > Y And Y
>Z Then
‘Do Something
End If

One has to keep in mind, though, that this merging of conditions may not always
be appropriate. In fact, in some cases, it may even result in an error.

Because VB evaluates an entire statement, a programmer would most likely


encounter an error when the second half of a condition relies on the existence of
an object or property for which you’re testing in the first half of the condition

34 VISUAL BASIC: An Approach to Program Development

S-ar putea să vă placă și