You are on page 1of 103

VISUAL PROGRAMMING

VISUAL BASIC 6

BASIC
means Beginners' All-purpose Symbolic Instruction Code

Procedural fashion
But VB is event-driven
It uses the VB IDE
VBA
VBScript

(Integrated Development Environment)

- Visual Basic for Applications

Defining basic terms


Application
An application is a collection of objects that work together to accomplish
something useful. In VB the application is called a Project.

Object
An object is a piece of software that has properties and functions that can
be manipulated. A window is an object.

Event-driven
An event is something that happens - the user clicks on a button, a form
is opened, and the result of a calculation is too large.

Advantages of VB
1. VB applications are event-driven
2. VB supports the principals of objected-oriented design
3. VB is a complete windows application development
system

4. VB uses ActiveX controls, dynamically linked libraries


(DDL) and add-ins.

Different type of projects


Standard

ActiveX Document EXE

ActiveX EXE

DHTML Application

ActiveX DLL
ActiveX Control
Data Project
IIS Application
ActiveX Document DLL

Standard : this project contains the standard set of controls and is used
to create a basic windows application or to start a large application
project.
ActiveX EXE : This project helps you create an ActiveX executable
component that can be executed from other applications.
ActiveX DLL : An ActiveX DLL is used to contain controls and class
code that can be used in other projects.
ActiveX Control : This enables you to create a custom ActiveX control.
Data Project : This project starts with database components already
added to project file.

IIS Application : This project is used to create an Internet Application.


ActiveX Document DLL : This is used to by VB applications that will be
installed and executed from the Internet.
ActiveX Document EXE : This project is used to create an Internetbased VB application
DHTML Application : This project creates a Web/HTML based
application that can be executed only in a web browser.

Different Components of a Project


1. Form (.frm)

7. ActiveX Controls (.ocx)

2. Class (.cls)

8. ActiveX Designers(.dsr)

3. Standard(.bas)
4. Resource(.res)
5. ActiveX documents(.doc)

6. User controls(.ctl) and Property Pages(.pag)

From (.frm): form file contains the textual descriptions of the form
and its controls, including their property settings. These files also
have form level declarations for constants, variables and
procedures.

Class (.cls) : it is similar to a form file, except they have no visible


user interface. You can create your own objects.

Standard (.bas) : These files contain public or module-level


declarations of types, constants, variables and procedures.

Resource (.res) : A resource file can be contain bitmaps, text string


and other data that you can change without having to re-edit and
then recompile your program code.

ActiveX documents (.doc) : These are similar to form files but


are displayable only in an internet browser.

User controls(.ctl) and Property Pages(.pag) : These are


similar to form files but are used to create custom ActiveX controls
and their associated properties.

ActiveX Controls (.ocx) : These are optional controls that you


can add to the toolbox and then use on the programs forms.

ActiveX Designers (.dsr) : These files are any of the new


designer components available in VB (such as Data Environment
Designer or Data Report Designer).

ActiveX documents (.doc) : These are similar to form files but


are displayable only in an internet browser.

User controls(.ctl) and Property Pages(.pag) : These are


similar to form files but are used to create custom ActiveX controls
and their associated properties.

ActiveX Controls (.ocx) : These are optional controls that you


can add to the toolbox and then use on the programs forms.

ActiveX Designers (.dsr) : These files are any of the new


designer components available in VB (such as Data Environment
Designer or Data Report Designer).

ActiveX documents (.doc) : These are similar to form files but


are displayable only in an internet browser.

User controls(.ctl) and Property Pages(.pag) : These are


similar to form files but are used to create custom ActiveX controls
and their associated properties.

ActiveX Controls (.ocx) : These are optional controls that you


can add to the toolbox and then use on the programs forms.

ActiveX Designers (.dsr) : These files are any of the new


designer components available in VB (such as Data Environment
Designer or Data Report Designer).

IDE

The Visual Basic development environment contains


these programming tools and windows, with which
you construct your Visual Basic programs:
Menu bar
Toolbars
Visual Basic toolbox
Form window
Properties window
Project Explorer
Immediate window
Form Layout window

Programming Tools
1. Menu bar
Located at the top of the screen, the menu bar
provides access to the commands that control the
Visual Basic programming environment.
Menus and commands work according to standard
conventions used in all Windows-based programs.

Programming Tools
2. Toolbars

Located below the menu bar, toolbars are collections


of buttons that serve as shortcuts for executing
commands and controlling the Visual Basic
development environment.
You can open special-purpose toolbars by using the
View menu Toolbars command.

Programming Tools
3. Windows taskbar
This taskbar is located along the bottom of the screen.
You can use the taskbar to switch between Visual
Basic forms as your program runs and to activate
other Windowsbased programs.

Toolbox Controls
You use special tools, called controls, to add
elements of a program user interface to a form.
These resources in the toolbox, which is
typically located along the left side of the
screen.
(If the toolbox is not open, display it by using
the Toolbox command on the View menu.)

Toolbox Controls

Form Window
When you start Visual Basic, a default form
(Form1) with a standard grid (a window
consisting of regularly spaced dots) appears in
a pane called the Form window.
You can use the Form window grid to create
the user interface and to line up interface
elements.

Form Window

Form Window
Building Interface Elements
To build the interface elements, you click an interface
control in the Visual Basic toolbox, and then you draw
the user interface element on your form by using the
mouse.
This process is usually a simple matter of clicking to
position one corner of the element and then dragging to
create a rectangle the size you want.
After you create the element say, a text box you
can refine it by setting properties for the element.
In a text box, for example, you can set properties to
make the text boldface, italic, or underlined.

Properties Window
With the Properties window, you change the
characteristics (property settings) of the user interface
elements on a form.
A property setting is a characteristic of a user
interface object.
For example, you can change the text displayed by a
text box control to a different font, point size, or
alignment.

Properties Window

Properties Window
Properties Window Elements
The Properties window contains the following
elements:
A drop-down list box at the top of the window, from
which you select the object whose properties you
want to view or set.
Two tabs, which list the properties either
alphabetically or by category.
A description pane that shows the name of the
selected property and a short description of it.

Project Window
A Visual Basic program consists of several files that
are linked together to make the program run.
The Visual Basic 6.0 development environment
includes a Project window to help you switch back
and forth between these components as you work on
a project.

Project Window

Project Window
Project Window Components
The Project window lists all the files used in the
programming process and provides access to them
with two special buttons: View Code and View
Object.

Code Window
This computing logic is created using program
statements

keywords,identifiers,
and
arguments that clearly spell out what the
program should do each step of the way.
You enter program statements in the Code
window, a special text editing window designed
specifically for Visual Basic program code.
You can display the Code window in either of two
ways:
By clicking View Code in the Project window.
By clicking the View menu Code command.

Form Layout Window


The Form Layout window is a visual design tool.
With it, you can control the placement of the forms in
the Windows environment when they are executed.
When you have more than one form in your program,
the Form Layout window is especially useful you
can arrange the forms onscreen exactly the way you
want.
To position a form in the Form Layout window,
simply drag the miniature form to the desired location
in the window.

Form Layout Window

Understanding the project explorer window


It displays all the projects components in a hierarchical list. There are three

display options. View code, View object and Toggle folders.

Setting Project options


In VB we can set different properties associated with the project. It has
three to five tabbed pages, depending on the type of project. These are
general, make, compile, component and debugging tabs.

VB Procedures

Two types of procedures in VB are SUBROUTINES and FUNCTIONS

Rules

Unique name
Not same as VB keywords or Built-in VBprocedures.
A procedure can't contain other procedures within it.But can cal
another procedure at any time

Understanding Subroutines
A subroutine (SUB) is a set of programming statements that is
executed as a unit by VBA engine.
Example:
Private Sub Form_Load()
Dim sSQL As String
.
.
.
.
.
.

subroutine declaration
Declarations

Call fillcontros

call another subroutine

End Sub

Subroutine terminator

Components of VB Sub or Functions are


Declaration
Declarations area
Statements
Call to another procedure
Terminator : END key word followed by the
type of procedure

Understanding functions
It is similar to subroutine. The main difference is that a function returns a
value. That means it returns the value through its name.

Example:

Public Function VerifyUser( Name as string) as Boolean


If UName= mes college then

VerifyUser = True
Else
VerifyUser = False
Endif
End Function

Understanding Comments
A comment is a plain text message you embed in the midst
of your VBA code. A comment can include any printable
character but must begin with a single quote () or the key
word Rem (Shorthand for remark).

Using the Visual Basic Editor


ie is Visual Basic Code window. Its parts are

Project name

it appears in the code windows title bar.

Module name

it also appears in the code windows title bar.

Object list

it has direct access to the form and all the


controls on them. It contains the names of all
controls on the form, stored alphabetically.

Procedure list

it contains all the corresponding event procedures


for that control.

Declaration area

at the top of every module is an area reserved for


declaring variables and constant used within the
module.

Indicator bar

it is a vertical gray area along the left side of


the code window.

Procedure and full module view buttons :


it shows procedure wise ie. only one procedure and
all procedure view.

Procedure separator:

this is a thin horizontal gray line drawn between


procedure in the code window.

Procedure

this module can contain any number of procedures.

Private Sub Form_Load ( )


Form1.show
Print Welcome to Visual Basic tutorial
End Sub

Opening the Code Window


First and easiest method is double-click any control on the design view
An alternative path to the Code window is press F7
Right-click on the object and select the view code
Right-click the name of a form in the projects window and select view code

Click the view code button at the project windows toolbar to open the module
Crtl+F4 to close the code window and Alt+F4 shuts down VB

Understanding Code Window Features


Line continuation character underscore character, it is shown that
any line of code ending in an underscore character preceded by a
space is recognized as a statement that is continued on the next
line.
Concatenation character &
sSQL = "SELECT FirstName, LastName, " _
& "Title, HireDate, Extension " _
& "FROM Employees " _
& "ORDER BY LastName"

VBA code window color cueing to set aside comments, keywords etc
Global find and replace you can search entire project ie all
standard modules, form modules, class modules etc.

Setting bookmarks in code


This is useful for quickly jump between different locations in your VBA
code.
Toggle Bookmark

this add a bookmark to the current line of code window. If a


bookmark previously set on that line will be removed.
Next bookmark

it moves the editing cursor to the next available bookmark.

Previous bookmark:
it moves the editing cursor to the previous available
bookmark.
Clear all bookmark:
removes all bookmark in all modules in the projects.

Using automatic word completion


VB can help you by completing long keywords as you type. As
soon as you have typed enough of keywords for VB to
determine which word you are typing, press Ctrl+Spacebar.

It does not recognize the names of procedures or variables you are


created in VB program.
If you are not entering enough characters for VB to fill in the rest
of the word, you will see a pop-up list of words to select from

Understanding Editor Options


Auto Indent

it causes code to be indented to the current depth in all successive


lines of code.

Auto Syntax Check:


if selected VB checks each lines of code for syntax errors as you enter
it in the code window. It checks spelling errors, missing commas and
so no.
Require Variable Declaration:
if selected, this setting automatically inserts the option explicit directive
into all VBA modules.
Auto List Members :

this timesaving option displays a list box that contains the members
of an objects object hierarchy in the code window.

Auto Quick Info

if it is selected VB displays syntax help when you enter


the name of a procedure( function,subroutine or method)
followed by a period, space or opening parenthesis.

Auto Data Tips

this option displays the value of variables when you hold the
mouse cursor over a variable with the module in break mode.

Drag-and-Drop Text Editing:


this setting toggles drag and drop editing.

Default to Full Module View:


by default code window shows more than one procedure if the
procedures are small enough to be seen in their entirely.
Procedure separator :
this the thin gray line that separates procedures in code
window.
Tab width

:
it specifies how many spaces will be inserted each time the
tab key is pressed.

Understanding the Editor Format Tab in the Options


Dialog Box
It contains settings that determine the overall appearance of
the code window.
Code Colors : the code window displays a variety of different
types of code statements.
Eg. Executable commands, comments beak point etc. There are
three color settings for each of the 10 different code structures in
the code window: foreground, background and indicator.
Foreground and background are self-explanatory.

Font and Size: this setting specify the font and font size used in code
window.

Margin Indicator Bar: it is the vertical, gray bar along the left side of the

code window.

Controlling Program Flow


Using Conditional Branching
A conditional branch executes blocks of statements depending on
the value of an expression.

Using if. . . then


If (condition) Then

Optional statement(s)
End If

Statement 1

Then
If
Expression

Statement 2

Optional Statement(s)

Example:
If/Then/End If blocks to allow multiple statements:
If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
End If
In this case, if Balance - Check is less than zero, two
lines of information are printed.

The following is an alternative way to write an if statement


If Balance - Check < 0 Then Print "You are overdrawn"

Here the optional statement appears on the same line as the


if , the end if statement isnt needed.

If . . . then . . . Else
If (expression/condition) then
Statement(s) if expressions is true
Else
Statement(s) if expressions is false

End If

Statement 1

Else
Statement(s) if
Expression is false

If
Expressio
n
Then
Statement(s) if
Expression is true

End If

Statement 2

Example:
If/Then/Else/End If blocks:
If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
Else
Balance = Balance - Check
End If
Here, the same two lines are printed if you are
overdrawn (Balance - Check < 0),
but, if you are not overdrawn (Else), your new
Balance is computed.

Example:
Public Function VerifyUser(UName As String) As Boolean
If UName = "Bob Smith" Then
VerifyUser = True
Else
VerifyUser = False
End If
End Function

If . . . then . . . ElseIf . . . End If


If (expression 1/condition 1) then
Statement(s) if expressions 1 is true
Else If (expression 2/condition 2) then
Statement(s) if expressions 2 is true

Else If (expression N/condition N) then


Statement(s) if expressions N is true
End If

Statement 1

Else

Else
If
Expressio
n2

If
Expressio
n1

If
Expressio
nN
Then

Then

Then

Statement(s) if
Expression 1 is true

End If

Statement 2

Statement(s) if
Expression 2 is true

Statement(s) if
Expression N is true

Example:
the ElseIf statement:
If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
ElseIf Balance - Check = 0 Then
Print "Whew! You barely made it"
Balance = 0
Else
Balance = Balance - Check
End If

Using Select Case


The expression is evaluated at the top of the select
case statement and compared with each of the
candidate values in the body of the select case.
If none of the values match the expression, the select
case simply ends.
An option Case Else can be added to the Select Case
body to trap in the body to trap those instances where
none of the candidate values match.

Statement case
Expression

Statement Block 1

Case
Value 1

Statement Block 2

Case
Value 2

Statement Block N

Case
ValueN

End Select

Example:
Sub SelectCase(sPet As String)
Select Case sPet
Case "Dog
MsgBox "It's a dog
Case "Cat
MsgBox "It's a cat
Case "Bird
MsgBox "It's a bird
Case Else
MsgBox "Unknown pet
End Select
End Sub

Loops
For . . . Next
Syntax

For initialize the counter variable to upper limit


[increment value]
Statement(s)

Next counter variable


Here increment value is optional and by defaults to 1.

For counter = start To end


statements
Next
1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control
passes to the statement after the Next; if not the statements are
executed.
3)At Next, counter is incremented and goes back to step 2).

Establish upper limit


and increment Value

Statement Block

Increment counter

No

Counter at
upper
limit?
YES

Continue processing
ie. Next statement

Example:
Public Function ValidatePassword2() As Boolean
Dim i As Integer
Dim sPWD As String
For i = 1 To 3
sPWD = InputBox("Enter the password")
If sPWD = "xyzzy" Then
Exit For
End If
Next i
If i <= 3 Then
ValidatePassword2 = True
Else
ValidatePassword2 = False
End If
End Function

Do. . . Loop
Here the statement block is preceded before the expression
is evaluated.
Syntax
Do
Statement 1
Statement 2
.
.
Statement n
Loop Until Expression Is- True

Statement 1

Process Statement
Block

No

Has
condition
been Met?
YES

Statement 2

Example:
Sum = 1
Do
Print Sum
Sum = Sum + 3
Loop Until Sum > 50

This loop repeats Until Sum is greater than 50.


And, like the previous example , a
Do/Loop Until structure always executes at least once.

Another do loop form is instead of Until we use While keyword


Syntax
Do
Statement 1
Statement 2
.
.
.
Statement n
Loop while Expression Is- False

Example

Sum = 1
Do
Print Sum
Sum = Sum + 3
Loop While Sum <= 50
This loop repeats While the Variable Sum is less than
or equal to 50.
Note, since the While check is at the end of the loop, a
Do/Loop While structure is always executed at least
once.

An alternate DoLoop logic is that expression is evaluated at the top


of the loop and statement block is never executed if the expression is
true.
Do Until Expression Is- True

Statement 1
Statement 2
.
.
.
Statement n
Loop

Statement 1

YES

Has
condition
been Met?

Statement 2

No

Process statement
Block

Example:
Counter = 1
Do Until Counter > 1000
Print Counter
Counter = Counter + 1
Loop
This loop repeats Until the Counter variable exceeds 1000.
Note a Do Until/Loop structure will not be entered if the Until
condition is already True on the first encounter.

Do While condition
statements
Loop
First, the condition is tested; if 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
Counter = 1
Do While Counter <= 1000
Print Counter
Counter = Counter + 1
Loop

Data type

Storage
size

Range

Byte

1 byte

0 to 255

Boolean

2 bytes

True or False

Integer

2 bytes

-32,768 to 32,767

Long (long integer)

4 bytes

-2,147,483,648 to 2,147,483,647

Single
precision
point)

(singlefloating-

4 bytes

Double
precision
point)

(doublefloating-

8 bytes

Currency

-3.402823E38 to -1.401298E-45 for negative values;


1.401298E-45 to 3.402823E38 for positive values

-1.79769313486232E308 to -4.94065645841247E-324 for


negative
values;
4.94065645841247E-324
to
1.79769313486232E308 for positive values

8 bytes

-922,337,203,685,477.5808
922,337,203,685,477.5807

Date

8 bytes

January 1, 100 to December 31, 9999

Object

4 bytes

Any Object reference

String

various

0 to approximately 2 billion

Variant

various

Same range as any numeric or string data type

to

Byte
A byte variable occupies only 8 bits. It can contain unsigned
whole number values from 0 through 255. Negative numbers
and numbers larger than 255 are not allowed. If do so it will
return overflow error.
Example
Byte

Dim bByte As Byte

Integer
It is similar to byte, except that its larger and can store negative
numbers. It occupies 16 bits. And can hold whole numbers
between -32768 to 32,767.

Long

It behaves exactly as integer values, except that it can assigned


much larger and much smaller values than integer. Because long
integer are 32 bits in size, they can hold positive and negative
numbers range between -2,147,483,648 to 2,147,483,647

Single

It contains floating point numbers. It can hold 32 bits. It is not


suitable for financial and scientific calculations.

Double

Double
It occupies 8 bytes of memory and can hold large and small
floating point numbers. It is used for calculation requiring
extreme precision.

Currency
It is reserved for storing numeric values such as bank account
balance, prices and payroll information.

Boolean
It accept only True or False values. It stores internally as
integer number. True is stored as -1 and false is 0.

Date
It contain only date and time data. It occupies 8 bytes and stored
internally as a floating-point number.

It hold all date and time values from January 1, 100 through
December 31, 9999 and time from 00:00:00 to 23:59:59 one
second increment.
If we convert numeric value to date, the portion of the number to
the left of the decimal point become the date and the decimal
point become time.

String
It can holds data made up of letters, numbers and symbols you
see on a keyboard. Visual Basic provides two type of string
variables.
Fixed length string and variable length string
Fixed length contains at most 65000 characters.
Variable length can be as long as 2 billion characters.
Example

Dim sFixed As String *10

a 10 character fixed width string.

Dim sVariable As String

a variable length string.

In fixed width string, the strings are fit the width defined for
the string. If we enter the word Bcollege to the sFixed
variable in the above example, then the data actually stored is
Bcollege ie. the fixed width contains unwanted spaces.

We can remove the unwanted spaces using different trim


functions. Ltrim which removes leading spaces, Rtrim-removes
trailing spaces and Trim removes both leading and trailing
spaces.

Object
There will be occasions when youll want to refer to a form on
a form in code or establish a variable that represents a
complex object with several different properties rather than a
single value. In such cases, the object data type is suitable.

Example
Private Sub Form_Load()
frmBuddy.Show
Call UpdateCaptions(Me, txtCaption1)
Call UpdateCaptions(frmBuddy, txtCaption2)
bChanged False
End Sub
Public Sub UpdateCaptions(frm As Object, txt As Object)
txt.Text = frm.Caption
End Sub
Specific object type references run faster than the generic object type.
Private Sub Form_Load()
frmBuddy.Show
Call UpdateCaptions(Me, txtCaption1)
Call UpdateCaptions(frmBuddy, txtCaption2)
bChanged = False
End Sub
Public Sub UpdateCaptions(frm As Form, txt As TextBox)
txt.Text = frm.Caption
End Sub

Variant
The default Visual Basic data type is Variant

It can accept any value.


It can hold more storage space than other data types.

Declaring Variables
There are two ways to add variables to your applications.

They are
Implicit declaration
visual basic automatically create the variables for you.
It means that Visual Basic automatically creates a variant
for each identifier it recognizes as a variable in an
application
Example
Private Sub cmdCombine_Click()
FirstName = txtFN.Text
LastName = txtLN.Text
txtFullName = FN & " " & LN
End Sub

Explicit declaration
- here we use one of the following keywords: Dim, Static, Private and
Public.
Syntax
Dim VariableName As DataType
Static VariableName As DataType
Private VariableName As DataType

Public VariableName As DataType

Example
Private Sub cmdCombine_Click()
Dim FirstName As String
Dim LastName As String
FirstName = txtFN.Text
LastName = txtLN.Text
txtFullName = FN & " " & LN
End Sub

Compare Implicit and Explicit Variable performance

Providing Names for your Variable


These are the rules to follow when naming elements in VB variables, constants, controls, procedures, and so on:
A name must begin with a letter of the alphabet.
The name must consist only of letters, digits and the
underscore character (no punctuation mark are allowed)

May be as much as 255 characters long


Variable name cant be duplicated within the same scope.

Forcing Explicit Declaration


Naming Convention
Example : boolActive or factive, txtLS

Under standing Variables Scope and Lifetime

Converting Between Data Types


Visual Basic provides several ways to convert values between
different data types.
Visual Basic automatically converts between the data types in
the expression.

Example
Public Sub Conversion1 ()
Dim sSt As String
Dim dDb As Double
sSt = "12345.67890"
dDb = sStr
MsgBox "Value of dDb: " & dDb _
& vbCrLf & vbCrLf _
& "TypeName(dDbl): " & TypeName(dDbl)
End Sub
This process of automatic conversion is called coercion
because Visual Basic forces the string value to a numeric
value.

Built-in conversion functions proved by the VBA language are


When passed the string 12345.67890
Function

Result

Resulting Data type

CByte

Overflow

Byte cannot contain a


value this large

CCur

12345.6789

Currency

CDate

10/18/33 4:17:36PM

Date/Time

Function

Result

Resulting Data type

CDbl

12345.6789

Double

CDec

12345.6789

Decimal

CInt

12346

Integer

CLng

12346

Long

CSng

12345.68

Single

CSrt

12345.67890

String

CVar

12345.6789

String

Objects
Characteristics
-building blocks of Visual Basic
- Object types already created - we make new instances
- Object types ' borrowed' from Windows environment
- Individual entities that are somewhat self-contained
- Can interact with other objects
- Some behavior 'built-in'

THANK YOU

You might also like