0% found this document useful (0 votes)
22 views40 pages

Vbnotes

The document discusses the tools and controls available in visual basic for designing forms and applications. It describes the toolbox which contains icons for different controls like command buttons, text boxes, and labels. It explains how to add controls to forms by dragging them from the toolbox and customize properties of forms and controls like captions, sizes, and positions. Key form properties discussed include caption, name, appearance, and borders. Properties of common controls like command buttons are also covered.

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views40 pages

Vbnotes

The document discusses the tools and controls available in visual basic for designing forms and applications. It describes the toolbox which contains icons for different controls like command buttons, text boxes, and labels. It explains how to add controls to forms by dragging them from the toolbox and customize properties of forms and controls like captions, sizes, and positions. Key form properties discussed include caption, name, appearance, and borders. Properties of common controls like command buttons are also covered.

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Visual programming

THE TOOLBOX
 The toolbox contains a set of tools we use to embellish a blank form. The tools for working
with a form are found on the menus; the toolbox itself contains the icons representing the
controls we can add to our forms.
 The toolbox is usually located on the far left of the VB screen, but it need not be visible at all
times.
 We can move the toolbox to another location on our screen using ordinary windows drag
and-drop techniques.

The Pointer

The first item on the toolbox is not a control but is used to manipulate controls after we create
them. Click the pointer when we want to select, resize or move an existing control. The pointer is
automatically activated after we place a control on a form.

Command Buttons

When we click a command button, it gives the illusion of being pressed. This optical illusion comes
from the shading used by VB for command buttons, and it is inherited from the windows operating
system.

Image Control

There is one of the two types of standard controls that we can use to display pictures.

Since image controls also recognize the click event, we can use them as graphical replacements for
command buttons. However, ordinary command buttons can also display pictures.
Textboxes

 We use text boxes to display text or to accept user input. Most of the code we write for the
text boxes is to process the information users to enter into them.
 Text boxes can word wrap automatically or display multiple lines of text.
 All the ordinary windows editing tools, such as cutting and pasting, are available when we
enter information in a text box.
 Text boxes can word wrap and may have scroll bars for moving through the text.
 The usual limit for a text box is approximately 32,000 characters.

Labels

 Use tables for information that users shouldn’t be able to change. Labels identify objects and
occasionally we might want to use them to display output.
 Although labels do respond to 12 events, usually they are used passively-for display
purposes only.

Creating controls

 We can always get a control on a form by double clicking on its icon in the toolbox. This gives
us the control in its default size and shape in the middle of the form. This is certainly one
way to proceed.
 We can use a combination of pointing, clicking and dragging to manipulate the toolbox.
 For example: to draw an item from the toolbox on a form at a specific location with a
specific size.
 The pointer control is automatically highlighted when we release the left mouse button as
well.

The name (control name) property:

This property determines the name VB uses for the event procedures we write to make the control
respond to the user.

For example:

Height=500 (or)

Me. height=5000

Then visual basic will always assume we mean to change the height of the current form.

If we wanted to change the height of a command button whose name property is


MyCommandButton, then

MyCommandButton. Height = 500

COMMON FORM PROPERTIES:


1. Caption
 The caption property sets the title of the form.
 The caption is also the title that a Microsoft window uses for the application icon when the
user minimizes the application.

2. Name

 This property is used only in code.


 The default value is, a rather prosaic, form1 and so its value start out the same as the default
value of the caption property.
 This property is mostly used in lager projects.

3. Appearance

 It determines whether the form will have a 3-dimensional look.


 If we leave it at the default value of 1, the form will look 3-dimensional change it to 0, the
forms will appear flat.

4. Border style

 It offers only a small number of choices.


 Set the border style value to 0-none and the application will show no border, therefore no
minimize, maximize or control box buttons. A form created without a border cannot be
moved, resized or reshaped.
 Change this setting to 1-fixed single and the user will no longer be able to resize the window.
All the user will be able to do is maximize or minimize the window.
 The default value, 2-sizable, allows the users to size and shape the form.
 The third setting, 3-fixed double, is not often used for ordinary forms, but it is commonly
used for dialog boxes. It gives a non-sizable border that is twice as thick as normal.
 The forth setting, 4-fixed tool window is not used very often. Under windows 95/98 and NT,
this displays the form with a close button.
 The fifth setting, 5-sizable tool window, work much like the fixed tool window setting. This
will display the form with a close button, and the text from the title bar will appear in a
reduced size.

5. Control box

 Changes to this property go into effect only when a user runs the application.
 As in any Microsoft window application, control boxes are located in the far left corner of
the title bar.
 Clicking the box displays a list of common window tasks, such as window minimizing,
maximizing and closing.
 We have only two choices: we can either have a control box or not.

6. Enabled

 If we set enabled to false, the form cannot respond to any event such as the user clicking on
the form.
 Usually we will use code to toggle this property back and make our form respond
dynamically.
 The properties window id most often used for setting the static properties of our objects and
not dynamic properties.

7. Text

 We can change the font style and size of the text given in the text box to display information
on the form.

8. Height, Width

 Height and width can be set two ways.


 Microsoft windows twips scale to measure the sizes o the objects involved.
 There are 1,440 twips to an inch.
 The term actually stands for one twentieth of a point.

9. Icon

 This property determines the icon our application will display when it is minimized on the
tool bar or turned into a standalone application on the windows desktop.

10. Left, top

 These properties determine the distance between the left or top of the form and the screen.
 Set the value of the top property to 0, the form designing is flush with the top.
 Set the value of the left property to 0, and it will be flush with the left side of the screen.
 Using the form layout window is, another way to control these properties.

11. Mouse pointer, Mouse Icon

 Mouse pointer is a useful property that lets us set the shape of the mouse pointer.
 The default value is 0, as the pull-down list indicates, there are 17 other values.
 Using a value of 11, hourglass changes the mouse pointer to the usual hour glass.
 Set the mouse pointer property to a value of 99 and we will be able to use a custom icon.
 This is most commonly done using code when the cursor is over a specific control.

12. Start-up Position

 This property gives us another way to decide on the initial position of our form at run time.
 It is generally more precise than using the form layout window.
 We have 4 choices; the most common is a setting of 2, which let us to centre the form on the
screen.

13. Visible

 Set the value to false, and the form will no longer be visible.
 We usually will want to make a form invisible only when we are designing an application
with multiple forms.
 We will often want to hide one or more of the form by using the visible property.
 Often, we will reset this property by using code and not at the time we design the
application.

14. Window State

 This property determines how the form will look at run time.
 There are 3 possible settings.
 A setting of 1 reduces the form to an icon, and a setting of 2 maximizes the form. A setting of
0 is the normal default setting.
 This property is most often changed in code.

PROPERTIES OF COMMAND BUTTON:


1. Caption

 The caption property of a form determines the name that shows in the title bar.
 The caption property on the command button determines what the user sees on the face of
the button.
 Any text we use for the caption on a command button is automatically centered within the
button.
 Command buttons always start out with caption like command 1, command 2, reflecting the
default value of the name property.
 The number indicates the order in which the button were created.
 Double-click on the command button icon to create the button in the center of the screen.
 The property window should be visible.

Eg:

Command1. Caption= click

2. Visible

 This property determines whether the command button is visible or not.


 It’s quite common to have our code alternately make a command button visible and
invisible, depending on the situation.
 Like the visible property for forms, this property can only be set to true or false.

3. Enabled

 This property determines whether the button can respond to any event.
 If we set property to false, VB will not respond to any event concerning that button.
 Unlike the visible property, the button remains on the form but is inert.
 The enabled property is more often temporarily toggled on or off via code than set in the
property window, thus maintaining flexibility in our program.
4. Font

 This property controls which font is used for the caption of the button.
 We can only use font at a time.
 When we open up the font dialog box, all the font characteristics- Bold, Italic, font name and
so on can be set independently for each command button.

5. Height, Width

 These properties define the Height and width of the command button.
 Microsoft windows twips scale to measure the sizes o the objects involved.
 There are 1,440 twips to an inch.
 The term actually stands for one twentieth of a point.
 We can change the settings for these properties window or by using the sizing handles.

6. Left, top

 These properties determine the distance between the command button and left edge and
top of the container.
 We can also change them by dragging and as with forms; the values are displayed to the
right on the toolbar.

7. Mouse Pointer

 Setting the mouse pointer to something different than the usual arrow is a good way to give
a user feedback that he or she has moved the focus to the command button.
 The same 17 settings that are available for the mouse pointer on the form are available for a
command button.
 8. Disabled Picture, Down Picture, Picture Style
 VB gives command buttons the ability to display graphics.
 In addition to giving a command button a picture in its normal state, we can set a special
picture when the control is disabled or when it is clicked.
 The command button won’t resize itself to fit the image, we will need to do that by hand.
 To make the command button display a picture, we first need to set the style property to 1.
 After that, we need only specify the picture to be used as the value of the other three
properties.
COMMON PROPERTIS OF TEXT BOXES:
 Text boxes are the primary method for accepting input and displaying output in VB.
 The icon in the tool box for a text box shows the letter ab.
 There are around 50 properties for text boxes.
 As before, the name property is used only for the code we write.

1. Height and Width, Left and Top

 As with command button the height, width, left and top properties use the scale determined
by the surrounding container.

2. Back color, fore color

 Unlike command button, we can set both the back color and fore color properties for a text
box.
 The fore color property affects the color of the text that is displayed.
 Back color affects the rest of the text box.
 Both of these can be set independently of the surrounding container.

3. Enabled

 The enabled property affects whether the text box will respond to events.
 If a text box is disabled, the user cannot enter the text inside it.
 When a text box is disabled it is greyed.

4. Visible

 It is quite common to toggle the visible property between true and false with code, in order
to make a text box appear and disappear.

5. Mouse pointer

 The mouse pointer property has the same 17 possible settings as for form.
 We can often change this property to dramatize that the focus is now within the control.

Special properties for text boxes:

 There are a few properties for text boxes and the border style property works differently
than for forms.

6. Text

 The text property in text boxes is the analog of the caption property for a command button
or a form; it controls the text the user sees.
 When we create a text box, the default value for this property is set to text 1, text 2 and so
on.
 If we want a text box to be empty when the application starts, select the text property and
blank out the original setting. Eg: Text1. Text=a

7. Alignment

 This property controls how text is displayed.


 The default value is 0, which leaves the text left-alignment.
 Use a value of 1 and text is right aligned.
 Use a value of 2 and text is centered.

8. Multiline

 This property determines whether a text box can accept more than one line of text when the
user runs the application and it is usually combined with resetting the value of the scroll bars
property.
 If we set this to true, a user can always use the standard methods in windows to move
through the text box: the arrow keys, home, ctrl+home, end and ctrl+end.
 VB automatically word-wraps when a user types more than one line of information into a
multiline text box, unless we have added horizontal scroll bar to the text box.
 If we have a default command button, the user has to press ctrl+enter to break lines.
 Since forms can only display a limited amount of text and they do not scroll, multiline text
boxes are the usual method for displaying large amounts of text in VB.
 The limit for a multiline text box is approximately 32,000 characters.

9. Scroll Bars

 This property determines whether a text box has horizontal or vertical scroll bars.
 VB allows us to accept long or multiple lines of data from a single text box, roughly 32,000
characters is the limit for a multiline text box.

10. Border Style

 As with the image control, there are only two possible setting for the border style property
for a text box.
 The default value is 1, which gives you a single-width border called a fixed single.
 If we change the value of this property to 0, the border disappears.

11. Max length

 This property determines the maximum number of characters the text box will accept.
 The default value is 0, which means there is no maximum other than the 32,000 characters
limit for multiline text box.
 Any setting other than 0 will limit the user’s ability to enter data into that text box to that
number of character.
12. Password Char

 The password char property lets we limit what the text box displays.
 The convention is to use an asterisk (*) for the password character.
 Once we set this property, all the user sees is a row of asterisks.
 This property is often combined with the max length property to add a password feature to
our program.

13. Locked

 This true/false property lets us prevent users from changing the contents of the text box.
 Users can scroll and highlight text but won’t be able to change it.
 Its advantage over setting the enabled property to false is that the box isn’t greyed.

COMMON PROPERTIES OF LABEL:


 Most common use for label is to identify a text box or other control by describing its
content.
 Another common use is to display help information.
 Labels have 34 possible properties.

1. Caption

 Labels have a caption property that determines what they display, the font being set via the
font property.
 The caption property is originally set to be the same as the default name property.
 At design time we can have one line to text, at most, as the caption for a label.
 We can add blank lines of text to a caption.

2. Height and Width, Left and Top

 As with command buttons, the height, width, left and top properties use the scale
determined by the surrounding container.

3. Font Color

 We can set the back color and fore color properties for a label.
 The fore color property affects the color of the text that displayed.
 Back color affects the rest of the label.
 Both of these can be set independently of the surrounding container.

4. Enabled

 The enabled property is not often used for labels.


 Its primary role is to determine whether the user can move the focus to the control that
follows the label in tab order.
5. Visible property

 It is quite common to have code toggle the visible property between true and false to make
a label appear and disappear.

6. Mouse Pointer

 The mouse pointer property uses the same 17 possible settings.


 This is rarely changed for labels, but one possibility is to change the icon when the user
moves from the label to the control that is being labelled.

Useful properties for label:

 There are five especially useful properties for labels, auto size and word-wrap, works slightly
differently than it does for text boxes.
 We can only use the word wrap property after we set the auto size property to true.
 Also, the border style property has one neat use that can give more polish to our application.

7. Alignment

 The alignment property for a label has three possible settings.


 The usual value is 0, which means the text in the text in the label is left-justified.
 Set the value of this property to 1, and the text inside the label will be right justified.
 Set the value to 2, and the text is centered.

8. Border style, Back style

 The border style property has the same two possible values as text boxes.
 The default value is 0, label do no start out with a border.
 Set the value to 1, the label resembles a text box.
 Using labels with a border style property a value 1 displays output.
 The back style property determines whether the label is transparent or opaque.

9. Auto size, Word wrap

 Unlike command buttons, labels can be made to grow automatically in a horizontal direction
to encompass the text we place in them.
 This is a function of the auto size property.
 The default value is false; we need to change it to true to take advantage of this neat
feature.
 If we also set the word wrap property to true, the label will grow in the vertical direction to
encompass its content, but the horizontal size will stay the same.

Message boxes:
Message boxes display information in a dialog box superimposed on the form. they
wait for the user to choose a button before returning to the application.
Message boxes should be used for short messages or to give transient feedback.
The simplest form of the message box commands looks like this.
MsgBox"the message goes in quotes"
Message boxes can hold a maximum of 1,024 characters,and visual basic
automatically breaks the lines at the right side of the dialog box.
We can add our own,more informative,title to a message box.for this,we have to use
the full form of the message box statement by adding two options to it.here is ths complete syntax for
the msgbox command:
MsgBox messageInBox,TypeofBox,TitleofBox
We combine three different groups of built_in integer constants to specify the kind of
message box.the first number controls what kind of buttons appear.
The following table summarizes this information.
SYMBOLIC CONSTANTS VALUE MEANING
vbOkOnly 0 Display Ok button only
vbOkCancel 1 Display Ok and Cancel buttons
vbAbortRetryIgnore 2 Display Abort,Retry&Ignore button
vbYesNoCancel 3 Display Yes,no and Cancel button
vbYesNo 4 Display Yes and No button
vbRetryCancel 5 Display Retry and Cancel button
vbCritical 16 Display Cirtical Message icon
vbQuestion 32 Display Warning Query icon
vbExclamation 48 Display Warning Message icon
vbInformation 64 Display Information Message icon
The next group of numbers contols which button is the default button for the box.This
is summarised in the following table.
SYMBOLIC CONSTANT VALUE MEANING
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
We can combine there options by adding the constants or values together.for
example,the statement
MsgBox "Example of buttons",vbokCancel+vbExclamation+-
vbDefaultButton2,"text message box"
Although message boxes do not have event procedures associated with them,it is
possible to determine which button was pressed by assinging the value of msgbox to a variable and
reading off the value.

Statements In Visual Basic:


Visual basic ignores case and spacing,except within quotations marks.it
capitalites the first letter of command words and often adds extra spaces for readability.
for example,no matter how we capitalize the command word print-
PRint,Print,print and so on -pressing ENTER will change into Print.
Statement in Visual Basic rarely use line number and each staement
generally occurs on its own line.
Lines are limited to 1,023 characters but a statement can be extended to the
next line by using the underscore character ( _ ) preceded by a space at the end of the line.

Example

MsgBox "please click a button so something will happen"-


VbOkOnly,"Test Button"

Print "This is an example of a line that won't fit on a single line of the page,so i
outdented it."

If we were entering these lines in visual Basic, in the first example we could
either omit the underscore and continue typing on one line, or we could use the underscore and press
ENTER after it.In the second example we would have to continue on one line until we reached the
closing quote.
Comments:
Comment statements are statements that helps to explain the code.
we have two ways to indicate a comment.the most common method is to use a single
quotation mark( ' )-
not the backward apostrophe found below the tilde( ~ ) but the one usually found below the double
quotation mark( " ).

Example:
Private sub Command1_click( )
'A comment describing the procedure could go here' and here
End sub

we can also use the older Rem keyword for a comment(comments are sometimes called
remark statement for this reason):

Private sub Command1_click( )


Rem comments describing the procedure would go here
Rem
End sub
If we want to add comments to the ends of the lines,it is easier to use the single
quotation mark because the form requries a colon before it.
example:
PrintForm :Rem A bit more
PrintForm :Dump the current window
everything on aline following a comment symbol or the Rem keyword is ignored.

The End statement:


When the visual Basic processes an E nd statement, the program stops.
In a stand_alone program,after the end statement,all windows opened by the
program is cleared from memory.
We can have as many end statements within a visual basic program,but it is good
programming practice to restrict the number of events that end a program.
Replacing any end statement in the other places with an upload Me statement.this
calls the queryUnload event for that form.

Variables:

Variables in Visual Basic hold information (values),visual basic sets up an area in the
computer's memory to store the information whenever we use a variable.
Variables names in Visual basic can be up to 255 characters long provided the frist
character is a letter,can include any combination of letters,numerals and underscore.
The following cable lists some possible variable names and indicates wheather they
are acceptable.

Base1_Ball Acceptable
1base_Ball Not acceptable-first character is not a letter
Base.1 Not acceptable-uses a period
Base&1 Not acceptable-includes&inside the name
ThisIsLongButOk Acceptable-Only 15 characters Long

All character in a variable name are significant,but case is irrelevant.BASE is the


same variable as base.
Choosing meaningful varaiable names helps document our program and makes the
inevitable debugging process easier.
For example:
InternalEarned=Total * InterestRate
is preety much self_documenting,where as
IE=7 * IR
is a whole lot more confusing
The one other restriction on variable names is that we can't use names reversed by
Visual Basic:
ForExample:
Print is not acceptable as avariable name.however,we can embed reserved words
within a variable's name.that is,PrintIt is a perfectly acceptable variable name.

Variable Assignment Statements:


Assignment statement are what we use to give a VB variable a (new) value.
Another way to think about assignment statements as a means of copying information
from a source to a destination.
Visual Basic uses an equal sign for this operation;
For example
InterestRate=0.5
sets the value of a variable named InterestRate to be .05.
The variable name always appear on the left of the equality sign, and the always
appears on the right.

Setting Properties with code:


If we want to change a property setting for a visual basic object with code,place the
object'sname followed by a period and then the name of the property on the left side of the equal sign,
and put the new value on the right_hand side:

Object.Property=value

for example:suppose we have a text button and want to blank it out in code rather than use the
properties window,then

Text1.text=" "
Since there is nothing between the quotation marks,the text assigned to this property is blank.
We can change the settings of aproperty via code as often as necessary.for example,if we wanted to
change the caption on nacommand button called command1 then,
Command1.caption="put new caption here"
If we wanted to set a button called command5 to be the first button in the tab order,we would add a
link like this to an event procedure,
Command5.TabIndex=0

Default Properties:

Every VB object has a default property(for example,text boxes have the text
property)when refering to the default property,we don't need to use the property name.

Forexample,we can enter


Text1="This is new text"
to change text property of atext box.

Boolean Properties:
Properties that take only the value true or false are called boolean properties.
forexample,the visible proprty of a con trol is a boolean property.thus the boolean
properties specify wheather a command button is visible.is enabled,or in the default cancel or
command button.
Boolean proprties are commonly used wherever we have an "on/off"situvation.
Visual basic has built_in constants for these important property values,called true and
false.A statement such as
Command1.visible=false
in an event procedure hides the command button by resetting the visible property to be false.
The control stays hidden until Visual Basic processes the statement
Command1.visible=true
As another example,if we want the TAB key to skip a control while a program is
running,change the tabstop property to false.
Control.tabstop=false

The Not Operator and Boolean Properties:


The usual way to toggle boolean properties is with the Not operator.suppose we have
a statement such as
Command1.visible=Not(command1.visible)
is an event procedure.
This statement works as current as follows:visual Basic finds the current value of
command1.visible,and then the Not operator reverses this value,that is,if the value was true,it
changes to false,and viceversa.

Data types:

There are various kinds of numeric data types,the string data type ,and even a
boolean data type.in fact,Visual Basic handles 14 standard types of data.
The data types inVB are:
 String
 Integer
 Long Integer
 Single Precision
 Double Precision
 Currency
 Date
 Byte
 Boolean
 Variant

String:

The string datatype holds characters.


It holds single character in astring or many character.
A variable holding a string is called a string variable,.
The method of identifying the variable of this type is to place a dollar sign ( $ )at the
end of the variable name.
String variable can theoritically hold about 2 billion characters.
The most common use of string variables is to pick up the information contained in a
textbox.
Eg: Astring Variable$
Integer:

Integer variable hold relatively small integer values between(-32,768 and32,767)


Integer arithmetic is very fast but is restricted to these ranges or you will get an error
message.
It uses the percent sign( % )at the end of the variable.
Eg: AnIntegerVariable%=3
Long Integer:
The long integer variable holds integer between(-2,147,483,648 and 2,147,483,647)
The identifier used for this variable is ampersand( & )
Long integer arithmetic is also fast and there is very little performance on modern
machines.
They take up twice memory per variable.
Eg: ALong IntegerVariable&=123456789

Single precision:
The least accurate is called single precision.
They have a decimal point,but you cav be sure of the accuracy of only seven digits.
Although the accuracy is limited,the size of these numbers is upto 38 digits.
The identifier used by this variable is an exclamation point( ! ).
Eg: Asingle PrecisionVariable!=12.345

Double precision:
The double precision data type is used when you need numbers with up to 16 places
of accurancy.
They also allow more than 300 digits.
You can rely only on first 16 digits.
The identifier used for this variable is pound sign(#)
Eg: Adoubleprecisionvariable #=12.345#
Double precision variables are mainly used in scientific calculations in VB.
Byte:
It can hold integers between 0 and 255.
It is also needed for handling binary files.
Boolean:
In boolean type we need data to be either true or false.
It is considered good practice to use this data type rather than integer for true/false
values.

Currency:
They are signed to avoid certain problem inherent in switching from binary fractions to
decimal fractions.
The currency type have 4 digits to the right of the decimal place and upto15 to the left
of decimal point.
The identifier used for this is at sign(@)
Eg: AcurrencyVariable@=12.345@
Date:
The date data type you a convinient way to store both date and time information for
anytime.
If we want to assume time,we can use ordinary AM/PM method or 24_hr clock
method.
The identifier used for this variable is two pound sign's( # #) to the beginning and in
the end.
Eg: Premillenium=# December 31, 1999 11:59 PM #
Premillenium=# december 31, 1999 23:59 #

Variant:
The variant data type is designed to stored all the different possible VB data received
in one place.
It doesn't matter whether the information is numeric , date/time, or string, the variant
type can hold it all.
In VB if we don’t tell the type of information a variable holds, it will use the variant
data type.

DECISION MAKING AND BRANCHING

A program is asset of statement, which is normally executed sequentially in the order


in which they appear.
When a program breaks a sequential flow and jumps to another part of the code. It is
called Branching.
The If statement is a powerful Decision making statement and is used to control the
flow of execution of statement,
The If statement may be implemented in different forms depending on the complexity
of conditions to be tested.
 Simple if
 If else
 Nested if
 Else if ladder
Simple if:
 The general form of a simple if statement is:

If(test condition) Then


Statement_block
End If

 The statement block may be a single statement or a group of statement.


 Flow chart:

True
Test
expression

False Statement block

Statement-x
 If the test expression is true the statement block will be executed. Otherwise the
statement block will be skipped and the execution will jump to the statement –x.
 It should be remembered that when the condition is true both the statement block and
statement –x are executed in sequence.
 Example:
If a=b Then
Print ”A and B are equal”
End If

If Else statement:
It is an extension simple if statement
The general form is

If(test condition) Then


True block statement
Else
False block statement
End If

 If the test condition is true then true block immediatetly following the if block is
executed.
 Otherwise the false block statement is executed.
 The either case either true block or false block will be executed, not both.
 Flow chart:

True False
test
exp

True block False block

Next statement

Example:
If a>b Then
Print “A is greater than B”
Else
Print “B is greater
End IF

Nesting of If statement:

When a series of decisions are involved, we may have to use more than one if else
statements in nested form.
General form:

If test condition1 Then


If test condition2 Then
Statement1
Else
Statement2
Else
Statement3
End If
End If

 If the condition1 is false, statement3 will be executed otherwise it continues to


perform second test.
 If the condition2 is true, statement1 is executed
 Otherwise statement2 will be evaluated and then the control is transferred to the next
statement.
 Flow chart:

false true
Test
exp

false true
Test
exp

Statement3 Statement2 Statement1

Example:

If(x>0) Then
If(y>0) Then Next statement
Print “ 1st quadrent”
Else
Print “ 4th quadrent”
Else
If y>0 Then
Print “ 2nd quadrent”
Else
Print “ 2nd quadrent”
End If
End If

Else if ladder:
There is another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each else
is an if.
General form:

If condition1 Then
Statement1
ElseIf condition2 Then
Statement2
.
.
.
.
ElseIf condition Then
statementN
Else
Statement default
End If

 The conditions are evaluated from the top to downwards.


 As soon as the true condition is found, the statement associated with it is executed and
the control is transferred to the statement-x.
 When all the N conditions are false, the final else containing the default statement will
be executed.

Flow chart:

entry

true
Test
exp1 false

true
Test
Statement1
exp2
false
Example:
Dim grade as string
If a>=80 Then
Grade=”A”
ElseIf a>=60 Then
Grade=”B”
ElseIf a>=40 Then
Grade=”C”
Else
Grade=”fail”
End If

Select Case:
This is also one of the multipath decisions statement.
It is executed like If ladder

General form:

Select case expression/variable


Case is condition1
Statement1
Case is condition2
Statement2
Case else
Statement-X
End select
 Select case is a built-in multiway decision making statement. It allows the program to
choose from more than two alternatives.
 The select case structure can be more efficient because it evaluates the test expression
only once. The result of the expression is then compared against multiple values to
determine which code block is invoked.
 One of several groups of statements ir run, depending on the value of an expression.
 It is ideal for testing the value of an expression against ranges of possible values.

 Flow chart:
entry

true
Test
exp1 false

ture
Test
Statement1
expN false

Statement N Default statement

Example:
Select case a
Next statement
Case is>=80
Grade=”A”
Case is>=60
Grade=”B”
Case is>=40
Grade=”C”
Case Else
Grade=”Fail”
End Select

Input boxes:
 Input boxes are alternative way of getting information from the user.
 This function displays a modal dialog box on the screen-just like the msgbox function.
 Modality is the principle advantage of input boxes; we sometimes need to insist that a
user supply some necessary data before letting him or he move on in the application.
 The disadvantages are that the dimensions of the input box are fixed beforehand, and
we lose the flexibility that textboxes provide.

Example:

Input Box X
This shows a sample input box
OK

Cancel

 Input boxes have a title bar that we can set. There is also a prompt; in the example
above, “This shows a sample input box”. There is always two command buttons
labeled OK and Cancel. Finally there is a text area at the bottom.

 The simplest syntax for the Input box function is:

String_variable=Inputbox(prompt_string)

This form uses the name of the project in the title bar of the input box.

 The full syntax for the input box function is:

Variable_name=Inputbox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

 Prompt parameter is a string or string variables whose value VB displays in the


dialog box. It is entitled to roughly 1024 characters.
 Title parameter is optional and gives the caption used in the title bar. There is
no default value; if we leave this out, the application’s name is used in the title
bar.
 Default parameter is also optional. It lets us display default text in the Edit box
where the user will be entering information. If we omit this, the box starts
empty.
 xpos and ypos are integral numeric expressions. xpos is the distance in twips
between the left edge of the input box and the left edge of the screen. Ypos gives
the distance in twips between the top of the box and the top of the screen.
 Helpfile and context are used together when we have message attached to the
box.
 Example:
String=Inputbox(“Example”, ”A default string”,100,200)

FORMAT FUNCTION:

This deals with decimal digits. This function works with a number and a template,
which is also called format string.

Syntax:
Format(Numeric Expression, Format string $)

Example:
Format(123.456789,”###.##”)
This yields a string 123.46. when we use a format string it rounds the number
so only two digits after decimal point will appear.

In general # is the placeholder for a digit except that leading and trailing zero are
ignored.
Example:
Format(123.450,”###.###”)
Yield 123.45
I
if we want to have leading and trailing zero, use a zero in place of # in format string.
Example:
Format(123.450,”000.000”)
Yield 123.450
Format(123.450,”0000.000”)
Yield 0123.450

If we want to display numbers with commas for every three digits,


Example: format(123456789.99,”#,###.##”)
Yields 123,456,789.99

If we need to display a symbol such as +,-,$,(,) or a space. We use it in format string


exactly in place we want it occur.
Example: format(Amount, “$##.##”)

We can use format function in any statement that accepts a string


Ex: ms=”your balance is” & format(current balance,”$###.##”)

Predefined Format Strings:


VB makes it easier to deal with most common formatting situations called formats to
the format function.
For example: we can use a statement
Format(Amount, ”currency”)
instead of
Format(Amount,”###,###.##”)
 In particular, the first format works better for products that are going to be
used in more than one country.
 One advantage of using named formats is VB automatically adjusts things like
thousands separator and currency symbol.

The following table summarizes the predefined numeric formats.

Format name Description


General Number Gives a string with no thousand separator
Currency Uses thousand separator and displays two digits to the right of
decimal point.

Fixed Displays atleast one digit to the left and two digit to the right of
decimal point.

Standard Uses thousands separator and atleast one digit to the left and two digit
to the right of decimal point.

Percent Gives the number in percentage form by multiplying with 100.


Always displays 2 digits to the right of decimal point.

Scientific Uses VB version of scientific notations


Yes/No Displays No if the number is 0, otherwise Yes.
True/False Displays False if number is 0, otherwise True
On/Off Displays off if number is 0, otherwise On.

Format function for Date and Time


The following table gives the various formats for dates and time.

Format name Description


General Date Displays a date and/or time. If there is no fractional part we get date.
If there is no integer part we get time. If there are both we get both.
Long Date Displays a date using the format that windows uses for full dates.
Medium Date Displays date using middle date format
Short Date Displays date using short date format
Long Time Displays time with hour, minutes, seconds
Medium Time Displays time in 12 hour format using only hours and minutes and
a.m./p.m.
Short Time Displays the time using a 24 hour clock

Example: Format(Now, ”General Date”)


Format(Now, ”Long Time”)
Date/Time Functions X
11/1/95 11:08:46 p.m.
Wednesday, November 01,1995
01-Nov-95
11/1/95
11:08:47 p.m.
11:08 p.m.
23:08

LOOPING:

¶ Looping structure allows to specify the condition under which the program should
execute a set of instructions respectively. In a looping, a sequence is executed until
some conditions for termination of the loop are satisfied.
¶ The program loop consists of two segments:
 Loop body
 Control statement
¶ The control statement tests certain conditions and then directs the repeated execution
of the statements required.
¶ Depending on the position of the control statement in a loop, a control structure may
be classified into:
 Entry controlled loop – conditions are met before loop
 Exit controlled loop – conditions are met after the execution of the loop once
¶ Visual basic supports two looping structure:
 Indeterminate looping
 Determinate looping

Indeterminate looping:
¶ The ability of the looping program to be executed for an indeterminate or infinite
number of times.
¶ Example of indeterminate looping is Do…Loop structure
Do..Loop structure:
There are several variations in Do…Loops. They fall in 2 categories: loops where the
expressions are:
 Evaluated at the end [exit check]
 Evaluated at the beginning [entry check]
Exit check loop:
Do…Loop While:
¶ This structure checks the condition after executing the block of code for a
single time.
¶ It repeats the code block until the test expression evaluates as FALSE
General syntax:
Do
[statements]
Loop while [condition]

Flow chart:
Entry

Loop body

Test True
exp

False

Example:
Do
Num=Inputbox(“Enter a number:”)
Loop while num>0
In the above example, the statement “Enter a number:” will be executed once. Later
the condition is checked, if the expression is TRUE, the loop is executed else the loop is
exited.

Do…Loop Until:
¶ This structure checks the condition after executing the block of code
¶ It repeats the code block until the test expression evaluates TRUE
General syntax:
Do
[statements]
Loop until [condition]

Flow chart:
Entry

Loop body

Test
False exp

True
Example:
Do
Loopcount=Loopcount+1
Loop until msgbox(“Loop..?”, vbYesNo)=VbNo
 In the above example, the Loopcount is incremented for the first time, and then
the condition is checked.
 The loop is executed until the condition evaluates to TRUE.

Entry Check Loop:


Do while loop:
¶ This structure checks the condition before executing the block of code.
¶ The code in the loop is executed only if the condition is True.
¶ Iteration is repeated until the test expression evaluates to FALSE.
General syntax:
Do while [condition]
[statements]
Loop

Flow chart:
Entry

Test False
exp

Loop body

True

Example:
Do while num>0
Num=Inputbox(“Enter an integer:”)
Loop
 In this example, the statement is executed only if the condition is TRUE.
 It repeats the code infinitely until the condition becomes FALSE.

Do Until loop:
¶ This structure checks the condition before executing the block of code.
¶ The code in the loop is executed if and only if the condition is false.
¶ Iteration is repeated until the test expression evaluates to TRUE.
General syntax:
Do until [condition]
[statements]
Loop

Flow chart:
Entry

Test True
exp

Loop body

False

Example:
Do until msgbox(“Loop..?”, vbYesNo)=VbNo
Loopcount=Loopcount+1
Loop
 In this example, Loopcount will be incremented only if condition is FALSE, else the
loop will terminate.

These entire Do…Loop structure are used when the specific number of times a block of code
should execute is not known.

Determinate looping:
¶ This looping structure allows to execute a block of code for a specified number of
times (or) finite number of times
¶ Example of determinate looping is For…Next structure
For…Next structure:
¶ It is an Entry Check Loop where the test condition is evaluated at the beginning
of code execution.
¶ For statement is used when the number of times the code block should be
executed is known
¶ It executes the code only for specific number of times.
General syntax:

For counter=start to end[step increment]


[statements]
Next [counter]

Execution of For…Next statement:


¶ The counter value is intialised. The variable counter is a loop variable
¶ Test condition is evaluated. It checks whether the starting value is less than the end
value. If TRUE, the code block is executed.
¶ After the executed of code, th loop variable is incremented by one by default. And
again the text condition is evaluated
¶ The loop is terminated when the condition becomes false.
¶ If the incrementing value should be increased from 1, then it can be achieved by using
Step Increment statement.
Flow chart:
Entry

Test False
exp

Loop body

True

Example:
For intcounter =1 to 32
Score=Inputbox(prompt:=”Enter Score”)
Totalscore=Totalscore+score
Next intcounter
 This loop code will be executed only for 32 times and get terminated at 33rd iteration.
Execution of code is thus Determinate.

ARRAY:

¶ An array is a representation of data in contigious area in the memory of our system.


An array consists of collection of elements of the same type that are referenced by a
common name.
¶ Each element in the array is distinguished by the ondex. All the elements in an array
must be of the same datatype. Each element of the array is reffered to by the array
name and the subscript or index.
¶ LBound and Ubound are built-in functions which return the lower and upper bounds
of an array.
One Dimensional Array:
¶ The idea of a one dimensional array is to give a systematic way to name groups of
related variables that are part of a list.
¶ To VB, a one dimensional array is just a collection of variables, each one of which is
identified by two things:
 The name of the array
 The position of the item on the list
¶ The number in the parenthesis is usually called a subscript, a pointer or most
commonly an index
Fixed array:
¶ In this the memory allocation stays the same for the whole time the programs runs.
¶ The advantage of a fixed array is that since a memory is set aside at the beginning of
the program, you run a much smaller risk of running out of memory while the
program is running.
Syntax:
Dim<array name>(index size) As<datatype>
Example:
Private sub form_load()
Form1.show()
Dim a(4) As integer
Dim num, counter as integer
For counter=0 to 4
Num=Num+1
a(counter)=num+2
print a(counter)
Next
End sub

Dynamic array:
¶ These are used to change the size of the array at runtime.
¶ You can resize a dynamic array at any time.
¶ It helps you to manage efficiently.
¶ After a dynamic array is initially declared, you can add new elements as needed.
¶ You can declare a dynamic array by giving it an empty dimensional list.
Syntax:
Dim<array name> () As<datatype>
Ex:
Dim a() As integer

ReDim statement:
This statement is used to resize the dynamic array at runtime. The redim statement
can appear only in procedure.
Ex:
ReDim a(4)
 Everytime the Redim statement is executed, the current values in the array are lost.
 VB resets all the elements to their default intial values. You can also shrink the size of
the array, to takeup minimal memory.
 However to change the size of the array without losing its contents preserve keywords
is used with ReDim statement.
Syntax:
ReDim preserve<array-name>(size)
Ex:
ReDim preserve a(5)

Multi dimensional array:

¶ Array with more than one dimensional is called multi dimensional array.
¶ Just as lists of data leads to a single subscript tables of data lead to double subscripts.

Example: multiplication tables:


Private sub command1_click()
Text1.text=val(text1.text)
For i=1 to val(text1.text)
For j=1 to val(text1.text)
Printi;”*”;”j”;”=”;i*j;chr(13)
Next j
Msgbox”click to continue”
Cls
Next i
End sub

 We can have index ranger in multi dimensional arrays, we obviously need versions of
LBound and UBound. The commands,
LBound(NameofArray, I)
UBound(NameofArray,I)
Give the lower and upper bounds for the I’th dimension of the array. Therefore,
Dim test%(1 to 5,6 to 10, 7 to 12)
Print LBound(test%,2)
Gives a 6 and
Print UBound(test%,3)
Gives a 12
One Dimensional Array With Index Rangers:
¶ VB has a command that eliminates the zeroth entry in all one dimensional arrays
dimensioned in a module or form.
¶ It is the OptonBase1 statement. This statement is used is in the declarations section of
a form or module, and it affects all one dimensional arrays dimensioned in that form
or module will begin with item 1.

Example:
optionBase1
dim a(), n, sum, i as integer
dim avg as double
n=Inputbox(“enter n”)
sum=0
ReDim a(n)
For I to n
a(i)=Inputbox(“Enter the array element”)
sum=sum+a(i)
next i
avg=sum/n
paint(sum)
print(avg)
End sub

Functions

Functions are set of statements that are used to perform certain operations.
Advantages of user-defined functions are:
1. It divides the entire program into smaller tasks.
2. It is used to avoid repetition of codings.
3.Debugging becomes easier.

Function Procedures :
* A procedure is a set of one or more program statements that can be executed by
referring to the procedure name.
* Calling refers to a program statement that instructs the compiler to execute a set
of statements stored as a procedure.
*The data values that the calling application supplies to a procedure are known as
argument.

Advantages of using procedures :


*The application is easier to debug because we can trace the source of an error to a
single procedure
* The code in a procedure is reusable because once the procedure has been tested
and stored. It can be called from any module.
Types of procedures :
Procedures are of two types. They are Sub procedures and function Procedures.
Sub Procedures :
Sub procedures can be further divided into two types. They are
General
Event

General Procedure :
These are special purpose blocks of code that perform a single task. We can create
general procedure in all types of modules. They can perform tasks common to all the
application such as connecting to a database.

Syntax:
[Public/Private] Sub<Procedure name>[argument]
Statements
End Sub

Example:
Public sub funcsqrt(num as Integer)
Print sqr(num)
End sub

Creating a General Procedure :

Press F7 or open the code window by double clicking anywhere in the form.
Select Tools menu in that select Add Procedure
In Add procedure dialog box give the Name of the procedure in the text box and select Sub
radio button.
Then Click OK button.

Event Procedure :
Event procedure is a block of code that are executed when a specific event occurs,
such as a command button is clicked or a form is loaded into the memory. Events are
associated with both controls and forms.

Syntax :
Private Sub<object name -event name > ([arguments])
Statements
End Sub

Example :

Private Sub CmdAdd_Click()


Txtno.Italic = True
End Sub
We need to use the code window to create the declaration for all the event procedures

Function procedures :

A function procedure like a sub procedure is used to execute a set of statements.It


can take arguments and also change the value of the arguments, but unlike a sub
procedure , it can return values to the calling procedures.

Syntax :

[Private/Public][Static] Function <function Name>[as <data type>]

Statements

End Function

Where data type specifies the return type of a function. The return value is used to indicate
the success or failure of the function and to pass the results of the processing occurring
within the function to the calling procedure. To return any value from the function we
should assign the value in the name of the function.

Example :

Public Function sqrt1(num as Integer) as Double


Sqrt1=Sqr(num)
End function

Creating a function procedure:

Press F7 or Open the code window by double clicking anywhere in the form.
Select Tools Menu in that Select ADD pocedure
In Add procedure dialog box give the name of the procedure in the text box and
select Function radio button. Then Click OK.

Calling a function or Procedure

While calling a function or procedure there are two ways of passing the procedures.
They are
Passing by reference
Passing by Value
Passing by Reference :

When we pass an argument by reference , any changes to the corresponding


parameter inside the procedure will change the value of the original argument when the
procedure is executed.

Example ;

Public Sub add1(a as Integer, b as Integer)


Dim aum as Integer
Sum=a+b
a=10
b=20
Print sum
End Sub
Sub form_load()
Dim a,b as integer
a=Inputbox(“Enter A”)
b= Inputbox(‘Enter b”)
Print “ Before calling the function”
Print a,b
Call add1(a,b)
Print “ After calling the function”
Print a,b
End Sub
Sub Program will not return a value.

Passing by value:

When we pass an argument by value, any change to the corresponding parameter


inside the procedure will not change the value of the original argument when the procedure
is executed. Here while calling a function or procedure the arugument should be closed by
parenthesis.

Public Sub swap(a as Integer, B as Integer)


Dim t as Integer
t=a
a=b
b=t
End Sub

Form _load()
Dim a,b as Integer
a=Inputbox(“Enter A”)
b=Inputbox(“Enter B”)
Call swap((a),(b))
Print a
Printb
End Sub

The On Error Statement


The heart of error handling in VBA is the On Error statement. This statement
instructs VBA what to do when an run time error is encountered. The On Error
statement takes three forms.

On Error Goto 0
On Error Resume Next
On Error Goto <label>:

The first form, On Error Goto 0, is the default mode in VBA. This indicates that
when a run time error occurs VBA should display its standard run time error
message box, allowing you to enter the code in debug mode or to terminate the
program. When On Error Goto 0 is in effect, it is the same as having no enabled
error handler.

The second form, On Error Resume Next , is the most commonly used and
misused form. It instructs to ignore the error and resume execution on the next line
of code.. It simply instructs VBA to continue as if no error occured. However, the
error may have side effects, such as uninitialized variables or objects set to
Nothing. You do this by testing the value of Err.Number and if it is not zero
execute appropriate code. For example,

On Error Resume Next


N = 1 / 0 ' cause an error
If Err.Number <> 0 Then
N = 1
End If

This statement tests the value of Err.Number and assigns some other number to
N.

The third form On Error of is On Error Goto <label>:which tells VBA to


transfer execution to the line following the specified line label. Whenever an error
occurs, code execution immediately goes to the line following the line label. None of
the code between the error and the label is executed, including any loop control
statements.

On Error Goto ErrHandler:


N = 1 / 0 ' cause an error
'
' more code
'
Exit Sub
ErrHandler:
' error handling code
Resume Next
End Sub

The Resume Statement


The Resume statement instructs VBA to resume execution at a specified point in the
code. The Resume statement takes three syntactic form:

Resume
Resume Next
Resume <label>

The following code attempts to activate a worksheet that does not exist. This causes
an error (9 - Subscript Out Of Range), and the code jumps to the error handling
block which creates the sheet, correcting the problem, and resumes execution at the
line of code that caused the error.

On Error GoTo ErrHandler:


Worksheets("NewSheet").Activate
Exit Sub

ErrHandler:
If Err.Number = 9 Then
' sheet does not exist, so create it
Worksheets.Add.Name = "NewSheet"
' go back to the line of code that caused the problem
Resume
End If
The second form of Resume is Resume Next . This causes code execution to
resume at the line immediately following the line which caused the error.

On Error GoTo ErrHandler:


N = 1 / 0
Debug.Print N
Exit Sub

ErrHandler:
N = 1
' go back to the line following the error
Resume Next

The third form of Resume is Resume <label>: . This causes code execution to
resume at a line label. This allows you to skip a section of code if an error occurs.
For example,

On Error GoTo ErrHandler:


N = 1 / 0
'
' code that is skipped if an error occurs
'
Label1:
'
' more code to execute
'
Exit Sub

ErrHandler:
' go back to the line at Label1:
Resume Label1:

All forms of the Resume clear or reset the Err object.

You might also like