0% found this document useful (0 votes)
107 views

VB Notes Ug

The document provides an introduction to Visual Basic, including: - VB is a high-level programming language that evolved from BASIC and allows programming through a graphical interface rather than text. - With VB6, you can create many types of programs for business, education, games, and more depending on your objectives. - The VB integrated development environment includes tools like the toolbox, form window, project explorer, properties window, and code window to aid in programming.

Uploaded by

Veronica Safrina
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

VB Notes Ug

The document provides an introduction to Visual Basic, including: - VB is a high-level programming language that evolved from BASIC and allows programming through a graphical interface rather than text. - With VB6, you can create many types of programs for business, education, games, and more depending on your objectives. - The VB integrated development environment includes tools like the toolbox, form window, project explorer, properties window, and code window to aid in programming.

Uploaded by

Veronica Safrina
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

1.

1 INTRODUCTION TO VISUAL BASIC

Before we begin Visual Basic 6 programming, let us understand some basic concepts of
programming. According to Webopedia, a computer program is an organized list of instructions
that, when executed, causes the computer to behave in a predetermined manner. Without
programs, computers are useless. Therefore, programming means designing or creating a set of
instructions to ask the computer to carry out certain jobs which normally are very much faster
than human beings can do.
A lot of people think that computer CPU is a very intelligent thing, which in actual fact it
is a dumb and inanimate object that can do nothing without human assistance. The microchips
of a CPU can only understand two distinct electrical states, namely, the on and off states, or 0
and 1 codes in the binary system. So, the CPU only understands the combination of 0 and 1 code,
a language which we called machine language. Machine language is extremely difficult to learn
and it is not for us laymen to master it easily. Fortunately, we have many smart programmers
who wrote interpreters and compilers that can translate human language-like programs such as
BASIC into machine language so that the computer can carry out the instructions entered by the
users. Machine language is known as the primitive language while Interpreters and compilers
like Visual Basic are called high-level language. Some of the high level computer languages
beside Visual Basic are Fortran, Cobol, Java, C, C++, Turbo Pascal, and etc .

VISUAL BASIC
VISUAL BASIC is a high level programming language which evolved from the earlier
DOS version called BASIC.BASIC means Beginners' All-purpose Symbolic Instruction Code. It

is a very easy programming language to learn. The code looks a lot like English Language.
Different software companies produced different versions of BASIC, such as Microsoft
QBASIC, QUICKBASIC, GWBASIC, and IBM BASICA and so on. However, people prefer to
use Microsoft Visual Basic today, as it is a well developed programming language and
supporting resources are available everywhere. Now, there are many versions of VB exist in the
market, the most popular one and still widely used by many VB programmers is none other than

Visual Basic 6. We also have VB.net, VB2005, VB2008 and the latest VB2010. Both Vb2008
and VB2010 are fully object oriented programming (OOP) language.
VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main
divergence from the old BASIC. In BASIC, programming is done in a text-only environment and
the program is executed sequentially. In VB, programming is done in a graphical environment.
In the old BASIC, you have to write program code for each graphical object you wish to display
it on screen, including its position and its color. However, In VB, you just need to drag and drop
any graphical object anywhere on the form, and you can change its color any time using the
properties windows.

WHAT PROGRAMS CAN YOU CREATE WITH VISUAL BASIC 6

With VB 6, you can create any program depending on your objective. For example, if
you are a college or university lecturer, you can create educational programs to teach business,
economics, engineering, computer science, accountancy , financial management, information
system and more to make teaching more effective and interesting. If you are in business, you can
also create business programs such as inventory management system, point-of-sale system,
payroll system, financial program as well as accounting program to help manage your business
and increase productivity. For those of you who like games and working as games programmer,
you can create those programs as well. Indeed, there is no limit to what program you can create!
There are many such programs in this tutorial, so you must spend more time on the tutorial in
order to learn how to create those programs.

STEPS IN VB APPLICATIONS
Understanding the problem

Clearly define what the application is to do: purpose, inputs, processing, outputs.

Design screens
Visualize application running and design its user interface – sketch it on pape.r

Make a list of the controls needed, decide on their names, and write a description.

Define the values of each control's relevant properties.

Design actions behind buttons


Make a list of methods needed for each control (user actions they must respond to)

Create a flowchart or write pseudocode for each method.


Check the code for errors by walking through its execution (sketch screens and trace variables)

Build screens
Start Visual Studio and create forms and other controls

Write code for actions


Write code for event procedures and other methods of step 5.

Test correctness
Attempt to run the application and correct syntax errors Repeatedly run the program with test data
as input and correct any run-time or logical errors.

INTEGRATED DEVELOPMENT ENVIRONMENT(IDE)

Before you can program in VB 6, you need to install Visual Basic 6 in your computer.
You can choose to start a new project, open an existing project or select a list of recently opened
programs. A project is a collection of files that make up your application.
You'll notice that the IDE contains a main menu bar and several windows (toolbox, form,
project explorer, and properties). You can customize the IDE to some degree to work according
to your preferences, which I will address in the next section.
The VB6 IDE (which was first introduced in VB5, and has not significantly changed in
VB6) is by default, an MDI (Multiple Document Interface) application, where the various
windows are "docked" at certain locations of the screen and can interlock with each other (for
example, the project explorer and the properties window are initially interlocked with each
other). This arrangement looks nice and organized upon first glance, and many people do prefer
working with VB using this default setup, or are not aware of the alternatives.

In earlier versions of VB, the IDE was an SDI (Single Document Interface), where each
Of these windows (toolbox, form, project explorer, and properties window) would float

"independently" on the Windows desktop. I found it easy to move from window to window to
get to what I needed, and it was particularly easy to design the forms. With the VB5/VB6 default
setup, I feel "boxed in" when designing a form, and if you move one of the other windows (like
the Properties window), you may find that it will "re-dock" itself in an area of the screen that you
didn't expect, re-arranging all of the other windows – this I find frustrating. Fortunately, the IDE
can be customized to use an SDI arrangement as well as to set other preferences.

PROPERTIES WINDOW

This window allows us to change some of the properties associated with an object at design time.
Displays all the properties of the object (relating to the active project, userforms or control) that
can be changed at design time.

(Shift + Tab) - jumps to the object field list


(Ctrl + Shift + X) - jumps to the first property whose name begins with the letter X
Note that some of these properties are read only and cannot be changed and others can only be
changed at run-time. When a code module is selected in the Project Explorer window the only
associated property is the name of the code module.
However when a user form or another object is selected then a list of properties will be
displayed.

Lists the design-time properties for selected objects and their current settings. You can change
these properties at design time. When you select multiple controls, the Properties window
contains a list of the properties common to all the selected controls.

WindowElementsObjectBox Lists the currently selected object. Only objects from the active
form are visible. If you select multiple objects, the properties common to the objects and their
settings, based on the first object selected, appear on the Properties List tabs.

PropertiesListTabs Alphabetic Tab - Alphabetically lists all properties for the selected object
that can be changed at design time, as well as their current settings. You can change the property
setting by selecting the property name and typing or selecting the new setting.
Categorized Tab - Lists all properties for the selected object by category. For example,
BackColor, Caption, and ForeColor are in the Appearance category. You can collapse the list so
that you see the categories or you can expand a category to see the properties. When you expand
or collapse the list, you see a plus (+) icon or minus (-) icon to the left of the category name.

FORM LAYOUT WINDOW

Form Layout window is a simple visual basic design tool whose purpose is to give the
user a thumbnail view of the current form. This helps in controlling the form position in the
Windows environment. When more number of forms are there in a particular program, this
―Form Layout‖ window is helpful to arrange all the forms onscreen, in exactly the way in which
the user needs them.
By simply dragging the miniature form to a particular location, the position of a form can be set
in the ―Form Layout‖ window.
Left and Top Properties

The screen location for form in Visual Basic can be set at design time using the Left and Top
properties in the ― Properties‖ window. These properties can also be set programmatically.
StartUpPosition Property

Visual Basic supports a property named ― StartUpPosition‖ which allows Windows to select a
location automatically. The Left and Top properties are taken by default.

CODE WINDOW

This displays the code associated with the item selected in the Project Explorer window.
Also sometimes referred to as a Module window.

You can even just double click the item in the Project Explorer window.
Displaying the Code Window

To display the code select the item in the Project Explorer window and either choose (View >
Code) or you can alternatively use the shortcut key (F7).
A code module will normally contain more than one procedure or function.
The IDE offers you a choice of whether to display the procedures one at a time (procedure view)
or all at one (full module view).
You can change the views by clicking on the small buttons in the lower-left corner of the code
window. Full Module view is the default.
You can minimise, maximise, hide and rearrange your code windows.

WORKING WITH FORMS IN VISUAL BASIC 6


The Appearance of Forms

The main characteristic of a Form is the title bar on which the Form's caption is
displayed. On the left end of the title bar is the Control Menu icon. Clicking this icon opens the
Control Menu. Maximize, Minimize and Close buttons can be found on the right side of the
Form. Clicking on these buttons performs the associated function.
The following figure illustrates the appearance of a Form

The control menu contains the following commands :


Restore : Restores a maximized Form to the size it was before it was maximized; available only
if the Form has been maximized.
Move : Lets the user moves the Form around with the mouse
Size : Lets the user resizes the control with the mouse
Minimize: Minimizes the Form

Maximize : Maximizes the Form


Close : Closes the Form

Setting the Start-Up Form


A typical application has more than a single Form. When an application runs the main Form is
loaded. By setting the Project properties you can control which Form is to be displayed in the
Start-Up of the application. Following figure illustrates the Project property window.

By default, Visual Basic suggests the name of the first Form created when the project started.
Loading and Unloading Forms
In order to load and unload the forms, Load and Unload statements are used. The Load statement
has the following syntax :
Load FormName
And the Unload statement has the following syntax :
Unload FormName
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show
method which cares of both loading and displaying the Form, the load statement doesn't show the
Form. You have to call the Form's Show method to display it on the desktop.
Showing and Hiding Forms
Show method is used to Show a Form. If the Form is loaded but invisible, the Show method is
used to bring the Form on Top every other window. If the Form is not loaded, the Show method
loads it and then displays it.
Syntax of the Show method of the Form
FormName.Show modeThe Formname
variable is the Form's name, and the
optional argument mode determines
whether the Form will be Modal or not.
It can have one of the following
syntax:
0-Modeless (default)

1-Modal

Modeless Forms are the normal Forms. Modeless Forms interact with the user and the user
allowed to switch to any other Form of the application. If you do not specify the optional mode
argument, by default the mode is set to modeless.
The Modal Forms takes the total control of the application where user cannot switch to any other
Forms in the application unless the Form is closed. A modal Form, thus, must have a Close
button or some means to close the Form in order to return to the Form where the Modal Form
was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
You must understand that the Forms that are hidden are not unloaded ; they remains in the
memory and can be displayed instantly with the Show Method. When a Form is hidden, you can
still access its properties and code. For instance, you can change the settings of its Control
Properties or call any Public functions in the Form.
The following is an example illustrates the Show method and Mode statement
Open a new Project and save the Project
Design the application as shown below

Object Property Setting

Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2
Caption Form3
Form
Name frm3
Click on a
Caption
button to display
Label
Name
a Form
Label1

The following code is typed in the Click event of the command buttons

Run the application. Clicking on the buttons will display the Forms respectively. But you can see
that in the cmd2_Click( ) event additionally VbModal argument has been added. You can see the
difference after you display the forms by clicking on the command buttons.
Finding out the difference between Unload and Hide method
To know what the difference is between Unload and Hide methods we will do an example. Open
a new project and save the project. Draw two buttons on the form and name those as shown
above.

In the click event of the Hide button Following code is entered. Me.Hide
In the click event of the Unload button following code is entered.
Unload Me
Save the project and run the application. Once you click on Hide button you can note that the
Form is invisible but the application is still running. But when you click on Unload button you
can see that the application is terminated.
Visual Basic 6.0- Properties, Methods And Events

All the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects
have associated properties, methods and events.
Real world objects are loaded with properties. For example, a flower is loaded certain color,
shape and fragrance. Similarly programming objects are loaded with properties. A property is a
named attribute of a programming object. Properties define the characteristics of an object such
as Size, Color etc. or sometimes the way in which it behaves. For example, a TextBox accepts
properties such as Enabled, Font, MultiLine, Text, Visible, Width, etc.
Enables property allows the TextBox to be enabled or disabled at run time depending on the
condition set to True or False.
Font property sets a particular font in the TextBox.
MultiLine property allows the TextBox to accept and display multiple lines at run time.
Text property of the TextBox control sets a particular text in the control.
Visible property is used to hide the object at run time.
Width property sets the TextBox to the desired width at design time.
The properties that are discussed above are design-time properties that can be set at the design

time by selecting the Properties Window. But certain properties cannot be set at design time. For
example, the CurrentX and CurrentY properties of a Form cannot be set at the design time.
A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. A complete definition
of cat must only encompass on its looks, but should also include a complete itemization of its
activities. Therefore, a cat's methods might be move, jump, play, breath etc.
Similarly in object-oriented programming, a method is a connected or built-in procedure, a
block of code that can be invoked to impart some action on a particular object. A method requires an object to
provide them with a context. For example, the word Move has no meaning in Visual Basic, but the statement,

Text1.Move 700, 400


Performs a very precise action. The TextBox control has other associated methods such as
Refresh, SetFocus, etc.
The Refresh method enforces a complete repaint of the control or a Form. For example,
Text1.Refresh refreshes the TextBox.
The SetFocus method moves the focus on the control. For Example Text1.SetFocus sets the
focus to TextBox control Text1.
EVENT DRIVEN PROGRAMMING
Visual Basic programs are built around events. Events are various things that can happen
in a program. this will become clearer when studied in contrast to procedural programming. In
procedural languages, an application is written is executed by checking for the program logically
through the program statements, one after another. For a temporary phase, the control may be
transferred to some other point in a program. While in an event driven application, the program
statements are executed only when a particular event calls a specific part of the code that is
assigned to the event.
Let us consider a TextBox control and a few of its associated events to understand the concept of
event driven programming. The TextBox control supports various events such as Change, Click,
MouseMove and many more that will be listed in the Properties dropdown list in the code
window for the TextBox control. We will look into a few of them as given below.
The code entered in the Change event fires when there is a change in the contents of the TextBox
The Click event fires when the TextBox control is clicked.
The MouseMove event fires when the mouse is moved over the TextBox.

Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence
like system generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of
events. An event is an action that calls a function or may cause another event. Event handlers are
functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
 Mouse events
 Keyboard events

 Mouse-Based Events
Mouse events occur when the mouse makes any movement in controls or the forms. The following are some

of the mouse-related events which are related to a control class.


i.  MouseEnter
This event gets triggered when the pointer of the mouse enters the control.

ii. MouseDown
This event gets triggered when the mouse button is pressed and the cursor is brought towards the downside of

it.

iii. MouseUp
This event gets triggered when the mouse pointer is over the control which is handling it and the already

pressed mouse button is released.

iv. MouseLeave
This is the event that gets triggered when the mouse pointer leaves the control.

v. MouseWheel
This event gets triggered when the wheel of the mouse moves and the control is provided the focus.

2. Keyboard Based Events


These are the events that are triggered when the events are fired upon any action done on the keyboard. This

includes actions such as keypress, keydown, enter, etc. Let us study some of the keyboard-based events in

detail.

i.  KeyDown
This event is a keyboard-based trigger that occurs when a key is pressed towards the downside and the control

has focus.

ii. KeyUp
This event is a keyboard-based trigger that occurs when a key is pressed towards the upside and the control

has focus.
iii. KeyPress
This event gets triggered when a particular key is pressed onto the keyboard.

VARIABLES

A variable is simply a name you give to an area of memory in which a data value used by your
program is stored. When you need to retrieve that data, or modify its value, you can refer to the
memory location by the variable's name.

Variable Type Description


Boolean 2-bytes, can contain the special values True or False
Byte 1-byte, unsigned integer 0 to 255
Currency 8-byte fixed-point. Stores 4 digits after the decimal point. Stores approx. +/- 922
trillion.
Date 8-byte date/time value from 1/1/100 to 12/31/9999.
Additional Info: Dates are stored internally as eight-byte Double Precision floating
point variables which can represent dates from January 1, 100 A.D. up to December
31, 9999. The integer portion holds the date with zero being December 30, 1899.
Dates prior to this are stored as negative values; those after as positive.
The February 12, 1997, for example, is stored as 35,473. The fraction portion holds
time information. Midday, for example, is represented as 0.5.
Double 8-byte floating point number (-1.79E+308 to 1.79E+308)
Integer 2-byte integer, stores approx. +/-32K
Long 4-byte integer, stores approx. +/-2 billion
Object A 32-bit (4-byte) address that refers to the location of an object.
Single 4-byte floating point number (-3.40E38 to 3.40E+38)
String Variable-length: 10 bytes + string length, holds up to 2 billion chars
Fixed-length: holds up to 64K chars
Variant Can hold any native data type, object reference, and the special
values Error,Empty and Null. Numeric variants require 16 extra bytes, string variants
require an extra 22.

The rules for forming a valid VB variable name are as follows:


The first character must be a letter A through Z (uppercase or lowercase letters may be used).
Succeeding characters can be letters, digits, or the underscore (_) character (no spaces or other
characters allowed).

The final character can be a "type-declaration character". Only some of the variable types can use
them, as shown below:

Data Type Type Declaration Character


String $
Integer %
Long &
Single !
Double #
Currency @

Use of type-declaration characters in VB is not encouraged; the modern style is to use the "As"
clause in a data declaration statement (described below).

The name can contain a maximum of 255 characters.

The name cannot be a reserved word (VB keyword).

VB is not case-sensitive: PAY, Pay and pay all refer to the same variable. If you type a
variable on a line in a case other than the case you used when you declared the variable, VB will
change the case to match that of the declared variable when you leave that line.

Variable Naming Conventions

As long as you stick to the rules above, VB is "happy"; however, many programmers follow
stylistic naming conventions in an effort to improve the readability of their code. The naming

conventions involve using a one-to-four character lower-case prefix to start off the name. The
purpose of the prefix is to identify the data type of the variable (like "int" for integers and "str"
for strings). These naming conventions are sometimes called "Hungarian naming conventions"
(after Charles Simonyi, an early Microsoft programmer – and Hungarian native – who proposed
the conventions). Two other prominent programmers, Leszynski and Reddick, also have led the
charge for naming conventions.
The chart below shows each variable type, a recommended three-character prefix, and a
sample variable name:

Variable Type Recommended Prefix Sample Variable Name


Boolean bln blnDataIsValid
Byte byt bytSmallNum
Currency cur curBigMoney
Date dtm (for "Date/Time") dtmEmpBirthDate
Double dbl dblAnnSalary
Integer int intCounter
Long lng lngBigIntValue
Object obj objExcelApp
Single sng sngHrlyRate
String str strMyWord
Variant vnt (or "var") vntWhatever

Variable Declaration in Visual Basic


You declare a variable to specify its name and characteristics. The declaration statement for
variables is the Dim Statement (Visual Basic). Its location and contents determine the variable's
characteristics.
For variable naming rules and considerations, see Declared Element Names (Visual Basic).

Declaration Levels

Local and Member Variables

A local variable is one that is declared within a procedure. A member variable is a member of a
Visual Basic type; it is declared at module level, inside a class, structure, or module, but not
within any procedure internal to that class, structure, or module.
Shared and Instance Variables
In a class or structure, the category of a member variable depends on whether or not it is shared.
If it is declared with the Shared keyword, it is a shared variable, and it exists in a single copy
shared among all instances of the class or structure.
Otherwise it is an instance variable, and a separate copy of it is created for each instance of the
class or structure. A given copy of an instance variable is available only to the instance for which
it was created. It is independent of a copy in any other instance.

DATA TYPE

The As clause in the declaration statement allows you to define the data type or object
type of the variable you are declaring. You can specify any of the following types for a variable:
An elementary data type, such as Boolean, Long, or Decimal
A composite data type, such as an array or structure
An object type, or class, defined either in your application or in another application
A .NET Framework class, such as Label or TextBox
An interface type, such as IComparable or IDisposable

Visual Basic type Common Nominal Value range


language runtime storage
type structure allocation

Boolean Boolean Depends on True or False


implementing
platform
Byte Byte 1 byte 0 through 255 (unsigned)

Char (single Char 2 bytes 0 through 65535 (unsigned)


character)

Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 throug


11:59:59 PM on December 31, 9999

Decimal Decimal 16 bytes 0 through +


79,228,162,514,264,337,593,543,950,335 (+//
7.9...E+28) †
with no decimal point; 0 through +
7.9228162514264337593543950335 with 2
/
places to the right of the decimal;
smallest nonzero number is +
0.0000000000000000000000000001 (+/-1E-28) †

Double(double- Double 8 bytes -1.79769313486231570E+308 through


precision floating- 4.94065645841246544E-324 † for negative values
point) 4.94065645841246544E-324 throug
1.79769313486231570E+308 † for positive values

Integer Int32 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

Long (long integer) Int64 8 bytes -9,223,372,036,854,775,808 throug


9,223,372,036,854,775,807 (9.2...E+18 †) (signed)

Object Object (class) 4 bytes on 32- Any type can be stored in a variable of type
Objec
bit platform
8 bytes on 64-
bit platform

SByte SByte 1 byte -128 through 127 (signed)

Short (short Int16 2 bytes -32,768 through 32,767 (signed)


integer)
Single(single- Single 4 bytes -3.4028235E+38 through -1.401298E-45 † f o
precision floating- negative values;
point) 1.401298E-45 through 3.4028235E+38 † f o
positive values

String(variable- String (class) Depends on 0 to approximately 2 billion Unicode characters


length) implementing
platform

UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)

ULong UInt64 8 bytes 0 through 18,446,744,073,709,551,61


(1.8...E+19 †) (unsigned)

User- (inherits Depends on Each member of the structure has a rang


Defined(structure) fromValueType) implementing determined by its data type and independent of th
platform ranges of the other members

UShort UInt16 2 bytes 0 through 65,535 (unsigned)

VB6 Variable Scope

The syntax for declaring a variable in VB is as follows:

[Dim | Private | Public | Static | Global]variablename [As datatype]

Note that you use one of five keywords to declare a variable; which one you use depends on
the scope you want the variable to have. There are three levels of scope:
project-level (also called "global" or "application" scope; the variable is accessible to all
procedures in all modules of the project)

module-level (the variable is accessible to all procedures in the module in which it is declared)

local-level (the variable is accessible only to the procedure in which it is declared)


In addition to the keyword used to declare the variable, the location of the variable declaration
also affects its scope. A variable may be declared in one of two places:

The General Declarations Section of a form or standard module. This section of a module is not
labeled as such; it simply exists at the beginning of a code module, after the "Option Explicit"
statement but prior to the first Sub or Function procedure. Declaring a variable here makes it a
project-level variable (if the Public or Global keyword is used) or a module-level variable (if the
Private or Dim keyword is used).

Within a Sub or Function procedure. Declaring a variable here makes it a local-level variable; only
the Dim or Static keyword can be used here. The recommended practice is to declare all local
variables within a procedure immediately following the Sub or Function header and prior to any
executable statements (although VB will allow you to declare variables anywhere within the
procedure).

The following table shows how the five different declarative keywords and the location
of their declaration affects the scope:

Keyword Where
General Declarations General Sub or Function procedure of
Used to Declared
Section of a Form Declarations a Form or Standard Module
Declare the
(.frm) Module Section of a
Variable:
Standard (.bas)
Module

Dim (preferred keyword module-level scope module-level local-level scope (value of the
for local-, but not module- scope variable is NOT preserved
level variables) between calls
Static not allowed not allowed local-level scope (value of the
variable is preserved between
calls)
Private (preferred keyword module-level scope module-level not allowed
for module-level variables) scope
project-level scope
Public (but references to the project-level scope not allowed

variable must be
qualified with the
form name; also there
are some minor
restrictions on the
types of variables that
can be declared as
public in a form)
Global (the use of this
keyword is discouraged; it not allowed project-level scope not allowed

remains only for


compatibility with older
versions of VB)

CONSTANTS
VB supports the use of symbolic, or named constants. Constants are similar to variables,
except that you provide a value for the constant when you declare it, and its value can never
change. The syntax for declaring a constant is:

[Public | Global | Private] Const constantname [As datatype] =expression

A global (project-level) constant can only be declared in a standard (.bas) module (not a form),
using "Public Const" or "Global Const" (the "Public" keyword is preferred). Module-level
constants can be declared in the General Declarations Section of either a standard or form code
module using "Private Const" (or just "Const"; the default is "Private"). Local-level constants are
declared in any procedure of a standard or form module just using the word "Const" (no "Public"
or "Private"). If you omit the "As datatype" clause, VB will use its "best guess" as to what the
datatype should be, based on the expression.
A constant is a meaningful name that takes the 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 constants that are defined by the controls or components you work with, or
you can create your own. Constants you create yourself are described as user-defined.
You declare a constant with the Const statement, using the same guidelines you would for creating a
variable name.

Scope of User-Defined Constants

A Const statement's scope is the same as that of a variable declared in the same location. You can
specify scope in any of the following ways:
 To create a constant that exists only within a procedure, declare it within that procedure.
 To create a constant available to all procedures within a class, but not to any code outside that
module, declare it in the declarations section of the class.
 To create a constant that is available to all members of an assembly, but not to outside clients
of the assembly, declare it using the Friend keyword in the declarations section of the class.
 To create a constant available throughout the application, declare it using the Public keyword
in the declarations section the class.

Compile-time and Run-time Constants

A compile-time constant is computed at the time the code is compiled, while a run-time constant
can only be computed while the application is running. A compile-time constant will have the same
value each time an application runs, while a run-time constant may change each time. 

The following table shows how constants may be declared and the location of their declaration
affects the scope:

Keyword Where
General Declarations General Sub or Function
Used to Declared
Section of a Form Declarations procedure of a
Declare the
(.frm) Module Section of a Form or
Constant:
Standard (.bas) Standard
Module Module
Const module-level scope module-level local-level
scope scope

Private Const module-level scope module-level not allowed


scope
Public Const
not allowed project-level scope not allowed
-or –
Global Const

Declaring Visual Basic Variables


Variables are declared using the Visual Basic Dim keyword. The syntax for a simple declaration
of a variable is as follows:
Dim variableName As variableType

In the above outline, Dim is the keyword which indicates to Visual Basic that a variable is being
declared. variableName is the name assigned to the variable. Try to use a descriptive variable
name and prefix the name with something which indicates the variable type. For example, when
declaring a String variable prefix the name with str (e.g. strFirstName). The As keyword
precedes the declaration of the variable type (String, Date, Integer etc).

Initializing Visual Basic Variables

Visual Basic variables may be initialized either during the declaration, or after the declaration.
Unless there is a good reason to do otherwise, it is recommended that variables be initialized
during the declaration.
Initialization is performed using the Visual Basic assignment operator (=). To initialize a single
variable when it is declared:
Dim intInterestRate As Integer=5
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 scope. 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
Global Scope
When a variable 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 section and must use the Public keyword.
The syntax for declaring a global variable is as follows:
Public variableName As dataType

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


Public Const constName As dataType

Static Variables in Visual Basic


When a variable is declared with Procedure level scope it only exists while the code in the
corresponding procedure is executing. Once the procedure completes, the variable and the
variable assigned to it are destroyed. Under certain circumstance it may be necessary for the
variable and the current value assign to it to persist beyond the life of the procedure. Next time
the procedure is called, therefore, the variable still holds the value it held on the previous
invocation of the procedure. The syntax to declare a static variable is as follows:
Static variableName As dataType

Conversion of Visual Basic data types


"Mixed mode" assignment statements were shown in a previous topic (i.e., a string was assigned
to an integer; a single was assigned to a string, etc.). VB would perform the necessary
conversions in these cases wherever it could. Such conversions are called implicit conversions.

In VB, you can also use a set of functions that explicitly convert (or "cast") one type of data to
another. The set of functions that enable you to do this all begin with the letter "C": CBool,
CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, and CVar. In addition, two older
functions, Val and Str, enable you to convert from a string to a number and from a number to a
string, respectively. Each function is described below:

CBool takes any valid expression and converts it to Boolean. Values of zero convert to False, all
others to True. If the expression is String, it must be a string that can be converted to a number
(like "123"). The strings "True" and "False" will also work; any other string will result in an
error.

ARRAYS
An array is a consecutive group of memory locations that all have the same name and the same
type. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger size
than required. We can declare an array of any of the basic data types including variant, user-
defined types and object variables. The individual elements of an array are all of the same data
type.
Declaring Arrays
Arrays are declared in the same manner as other variables (i.e., using the keywords "Dim",
"Private", "Public", etc.), except that the array bounds are coded in parentheses following the
variable name (if a fixed-length array is being declared) or an empty pair of parentheses follow
the variable name (if a variable-length, or dynamic array is being declared).
For fixed-length arrays, you must specify the upper bound of the array; you can
optionally specify the lower bound. By default, the lower bound is 0 (however, see the note on
the "Option Base" statement further below). For variable-length arrays, you do not specify any
bounds; you just code an empty set of parentheses.
Arrays can have up to 60 dimensions (although it is rare that you would have more than
three dimensions; one or two is the norm).
The syntax for declaring an array is:
[Dim|Private|Public|Static|Global] arrayname([lowerbound To] upperbound[,

…]) [As datatype]

Consider an example for one dimensional array


Print aintCount(4)
Consider an example for two dimensional array
Print asngSales(2, 3)
Print asngResults(0, 11, 5)
Initializing Arrays
Unfortunately, VB (up through version 6) does not provide a mechanism for initializing
arrays (or any variable) at the same time they are declared –initialization can only be done with
executable assignment statements. Older versions of BASIC (prior to VB) provided a pair of
statements (READ and DATA) that would enable you to load a set of constant data items into an
array fairly painlessly using a For/Next loop. But alas, READ and DATA were removed from
the language when VB came along.
ReDim Statement (Visual Basic)
Reallocates storage space for an array variable.

ReDim [Preserve] name (boundlist) [, name(boundlist) [, ... ] ]

Parts

Preserve
Optional. Modifier used to preserve the data in the existing array when you change the size of
only the last dimension.
name
Required. Name of the array variable. See Declared Element Names.
boundlist
Required. List of bounds of each dimension of the redefined array.

COMMENTS
The previous listing introduced a new syntax element: the comment. A comment is a line that is
NOT source code. Instead, it is there as guidance to the person reading the code. When
programmers write programs, they usually (or at least they should) add comments describing
large sections of code that could potentially be confusing. Comments begin with an apostrophe
("'") and end with a new line. Everything that you type after the apostrophe is ignored by Visual
Basic, which is the entire point of comments. You will see comments in all future listings
describingnewconceptsandsyntax.

CONTROL STATEMENTS:
Do-Loops

The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple:
Do
(Statements)
Loop
Exit Do
So we clearly need some way to escape from the Do-Loop. You could, of course, simply End the
program once you have calculated enough values, but what if you still need to perform tasks
after you're done calculating? The answer is to use the Exit Do statement. Whenever your
program reaches an Exit Do statement within a loop, it will exit the current loop.

Do Until
As an alternative approach to nesting an If-Statement inside the loop, and invoking Exit Do once
we're done looping, Visual Basic provides a Do Until statement. Its syntax is the following:

Do
(statements)
Loop Until (Expression)
(Expression) can be any legal logical expression that we wish to evaluate to determine whether
or not to exit the loop. Each time the program reaches Loop it will evaluate this expression. If the
expression is True, it will exit the loop for us, but otherwise it will continue looping..
Do While
In the place of Do Until, you can also use Do While. Its syntax is the following:

DoWhile(Expression)
(statements)
Loop
(Expression) can be any legal logical expression that we wish to evaluate to determine whether
or not to exit the loop. Each time the program reaches Loop it will verify that this expression is
True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is
True, it now exits only once this expression is false.
For-Next Loops
In situations where you merely want to run the loop a predefined number of times, it can become
quite tiresome to have to create and manage a counter for each loop, which is why we also have
something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to
count from one number to another each time through the loop, and to exit once the counter has
reached its upper limit. The syntax is as follow:
Dim I As Integer

For I = (Integer) To (Integer)


(Code to execute)
Next I
Exit For
As with Do Loops, there is a statement that can be used to exit a For-Next loop, and it is
called Exit For. Simply invoke this statement anywhere within a For-Next loop and the current
loop will be exited.
Select...Case Statement
Runs one of several groups of statements, depending on the value of an expression.
Select [ Case ] testexpression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Parts

Term Definition

testexpression Required. Expression. Must evaluate to one of the


(Boolean, Byte,Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single,
S

expressionlist Required in a Case statement. List of expression clauses representing match values forteste
are separated by commas. Each clause can take one of the following forms:
expression1 To expression2
[ Is ] comparisonoperator expression
expression
Use the To keyword to specify the boundaries of a range of match values fortestexpression.
than or equal to the value ofexpression2.
Use the Is keyword with a comparison operator (=, <>, <, <=, >, or >=) to specify
for testexpression. If the Is keyword is not supplied, it is automatically inserted before comp
The form specifying only expression is treated as a special case of the Is form wherecompar
form is evaluated as testexpression =expression.
The expressions in expressionlist can be of any data type, provided they are implicitly conve
the appropriate comparisonoperator is valid for the two types it is being used with.

statements Optional. One or more statements following Case that run if testexpression matches any clau

elsestatements Optional. One or more statements following Case Else that run if testexpression does not m
any of the Case statements.
End Select Terminates the definition of the Select...Case construction.

GOTO Statement:
The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is −

GoTo label

Flow Diagram

STRING:
Strings are enclosed in double quotes ( " " )

Strings are a data type

Strings are a collection of characters

Syntax

Dim stringName As String

VISUAL BASIC'S BUILT-IN FUNCTIONS

Visual Basic has many built-in functions for manipulating text and carrying out mathematical
operations, as well as the ability to format data in both standard and user-defined styles. We start
by looking at two functions that are both frequently used and at the same time relatively easy to
get to grips with - the MsgBox() function and the InputBox() function. We will then look at some
of the more commonly-used string-handling and math functions, and the ways in which
numerical, date and time values can be represented.

The MsgBox() function

The MsgBox() function displays a message in a pop-up message box (no surprises there!). The
user is expected to respond by clicking on a button in order to be able to continue. The format of
the statement used to invoke a message box is as follows:

returnVal = MsgBox (prompt, styleVal, title)

The prompt parameter is a string value (either a string literal or a string variable) that supplies
the message to be displayed. The styleVal parameter is either an integer style value from 0 to 5,
or a named constant that can be used instead of the corresponding integer value, that determines
which command buttons will appear on the message box. The title parameter is another string
literal or string variable that supplies the title for the message box.

The styles available are listed in the table below.

Message Box Styles


Style value Named constant Buttons displayed
vbOkOnly OK

vbOkCancel OK, Cancel

vbAbortRetryIgnore Abort, Retry, Ignore

vbYesNoCancel Yes, No, Cancel

vbYesNo Yes, No

vbRetryCancel Retry, Cancel

The returnVal value returned by the MsgBox() function is an integer value that indicates which
button the user has clicked in response to the message box being displayed. The possible return
values together with the named constants that may be used in their stead, are listed in the table
below.

Message Box Return Values


Return value Named constant Button clicked

1 vbOk OK
2 vbCancel Cancel
3 vbAbort Abort
Message Box Return Values
Return value Named constant Button clicked

4 vbRetry Retry
5 vbIgnore Ignore
6 vbYes Yes
7 vbNo No

The message box can be further embellished by the inclusion of an icon that will appear beside
the message. In Visual Basic, there are four icons available. The icon is included either by
incrementing the style value by a fixed constant value, or by the inclusion of a second named
constant (see table below).

Message Box Icons


Value Named constant Icon
16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

The following statements would produce exactly the same message box, and are essentially
equivalent to one another:

MsgBox ("This message is for info!", 64, "Info")


MsgBox ("This message is for info!", vbOKOnly + vbInformation, "Info")

The InputBox() function

The InputBox() function displays a pop-up input box into which the user can type a message. The
user is expected to enter their message, then click on a button ("Cancel" or "OK") in order to
continue. The format of the statement used to invoke an input box is as follows:

returnString = InputBox (prompt, title, defaultText, xpos, ypos)

The returnString returned by the InputBox() function is the text entered by the user. The prompt
parameter is a text string (either a string literal or a string variable) that prompts the user to enter

some information. The title parameter is another string literal or string variable that supplies the
title for the input box. The defaultText parameter can be used to enter default content in the input
box (although it would probably be left blank in most cases). The xpos and ypos parameters
specify the x and y coordinates for the input box on screen.

String functions

String Functions
Function Description
Returns n characters from the text string referred to by str, starting
Mid (str, pos, n) at character position pos.
Microsoft.VisualBasic.left Returns the n left-most characters from the text string referred to
(str, n) by str.
Microsoft.VisualBasic.right Returns the n right-most characters from the text string referred to
(str, n) by str.
Removes the white space (if any) at either end of the text string
Trim (str) referred to by str, and returns the result.
Removes the white space (if any) at the left-hand end of the text
LTrim (str) string referred to by str, and returns the result.
Removes the white space (if any) at the right-hand end of the text
RTrim (str) string referred to by str, and returns the result.
Looks for an occurrence of the substring str2 within the string
InStr (n, str1, str2) str1, starting at character position n. If successful, the function
returns the character position at which the substring is found (or
zero if the substring cannot be found).
Converts the string referred to by str to all upper-case characters,
UCase (str) and returns the result.
Converts the string referred to by str to all lower-case characters,
LCase (str) and returns the result.
Returns the ASCII character corresponding to the 8-bit character
Chr (charCode)

code charCode (note – some characters are non-printing characters,


and will not be visible on screen).
Returns the 8-bit ASCII character code corresponding to
Asc (character) character.

Maths functions

Maths Functions
Function Description
Math.Sqrt (n) Returns the square root
of a number, n. Math.Abs (n) Returns
the absolute value of a number, n.
Returns the exponential value of a number, n – i.e. e n.
Math.Exp (n) Note: e = 2.71828182
Fix (n) Returns the integer part of a floating point number, n.
Returns the integer part of a floating point number, n, for Int (n)
positive numbers, or the next smallest integer value for negative numbers.
Math.Log (n) Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value
between 0 and 1. Round (n,m) Rounds a number, n,
up (or down) to m decimal places.

Formatting numbers

The Format() function allows you to specify precisely how numeric values
are displayed. The function is used as follows:

Format (n, "styleArg")

The first argument (n) is the number to be formatted. The value selected for the
second argument ("styleArg") will determine how the number is displayed. The
possible values are described in the table below (note that a user-defined value
for "styleArg" can also be used).

Format () Number Style Arguments


Style Argument Description
"General Number" Displays n with no separator
between thousands. Displays n with no
"Fixed"
separator between thousands,
and rounds it up (or down) to two decimal places.
Displays n with separators
"Standard"
between thousands, and rounds it
up (or down) to two decimal
places.
Displays n prefixed by a "£" sign (if the locale is set
"Currency"

to United Kingdom) , with separators between thousands,


and rounds it up (or down) to two decimal places.
Displays n as a percentage, rounds it up
"Percent" (or down) to two decimal places, and
adds a "%" symbol.

FORMATTING THE DATE AND TIME

The Format() function can also be used to specify how date and time values are
displayed. The function is used as follows:

Format (Date, "styleArg")

The first argument (Date) is the date to be formatted (note that if you are
using the current date, the Now function can be used as the argument. The
value selected for the second argument ("styleArg") will determine how the
date value is displayed. The possible values are described in the table below
(note that a user-defined value for "styleArg" can also be used).

Format () Date Style Arguments


Style Argument Description
Displays the date and time in the format:
"General Date" dd/mm/yyyy hh:mm:ss
Displays the date in the format:
"Long Date" 06 October 2009
Displays the date in the format:
"Short Date" dd/mm/yyyy
Displays the
"Long Time" time in the
format:
h:mm:ss
Displays the time in the format:
"Short Time" hh:m

You might also like