Vbnotes
Vbnotes
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.
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.
2. Name
3. Appearance
4. Border style
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
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.
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.
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.
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.
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.
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:
2. Visible
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.
As with command button the height, width, left and top properties use the scale determined
by the surrounding container.
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.
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
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.
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.
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.
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.
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
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
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 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.
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.
Example
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):
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
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.
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
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:
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.
True
Test
expression
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 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
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:
false true
Test
exp
false true
Test
exp
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
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:
Flow chart:
entry
true
Test
exp1 false
ture
Test
Statement1
expN false
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.
String_variable=Inputbox(prompt_string)
This form uses the name of the project in the title bar of the input box.
Variable_name=Inputbox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
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
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.
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.
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:
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:
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)
¶ 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.
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.
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
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 :
Function procedures :
Syntax :
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 :
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.
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 :
Example ;
Passing by value:
Form _load()
Dim a,b as Integer
a=Inputbox(“Enter A”)
b=Inputbox(“Enter B”)
Call swap((a),(b))
Print a
Printb
End Sub
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,
This statement tests the value of Err.Number and assigns some other number to
N.
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.
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.
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,
ErrHandler:
' go back to the line at Label1:
Resume Label1: