Visual Programming Notes 2021
Visual Programming Notes 2021
Click "Standard EXE". Start a Standard .exe type of project. In the beginner
level, you will only learn about this type of project.
Other project types on this window are for the advanced learners. You can do
a lot of things implying VB6 is giving you enough power in your hand through
these different project types.
It is very important to know the names of all the elements of this development
environment. The tools available here makes it very easy for you to develop an
application. The VB6 IDE provides you many tools in one place. You can add a
control on the form of your choice, set a property of an object from the Properties
Window on the right hand side, set the form layout and many more things that
you can use alongside your coding. You can even fill the ToolBox with lots of
additional controls.
After adding a control to the form, you need to set its property and then write code
for the control to work how you want.
NOTE :
1. Pointer is not a control. Click this icon to select controls already on the form.
2. All controls are object
3. Form is an object, but it is not a control.
In the Properties Window, notice the help information about the object. This helps in
learning new properties.
(See Picture) Help information for the 'Caption' property is shown.
The Project Explorer Window gives you a view of the modules or forms which are
contained in your VB application. You can switch from one form to another or
from one module to another from the Project Explorer Window. You can view the
code window of a particular form or module as well.
The Form Layout Window shows where on the screen the form will be displayed
when the program will be executed. Simply drag on it so that the form appears
on the position where you want.
The Immediate Window helps in debugging your program by displaying the current
values of variables or expressions in a certain line of your code.
ToolBox
Label
The label control is used to display text. It is also used to label other
controls. The end user cannot edit the label text.
TextBox
The TextBox control contains characters. End-users can edit the characters
contained in the TextBox.
CommandButton
The CommandButton control is simply a button that we see in our daily-use
software. When the end-user clicks the CommandButton, the program
behaves according to the code assigned in the CommonButton.
Option Button
This control enables the end-user to select one among several options. Only
one option button among others in a group can be on at the same time. You
can name an option using the Caption property.
CheckBox
The CheckBox control is used to make a yes/no or true-false selection. You
can check more than one CheckBox at the same time that let you make
multiple choices. You can label this control using the Caption property.
Frame
The Frame control is used as a container of other controls. This is also used to
group different controls especially in Option Button controls when you wish to
select more than one option. The Caption property associated with it is useful
to label the frame.
Timer
The Timer control is not visible on the form when you run the program. It is
used to execute lines of code repeatedly at specific intervals.
You can set these properties either from Properties Window or you may wish to set
in run-time.
Example:
When you click on command1 button, the code in the Click event procedure is executed.
On execution, the background color of the label will be red and label's text color will
be blue.
Another example:
Example:
In this case, you have to copy the hexadecimal code from Properties Window.
Font
You can set the font property from the Properties Window. See the below example
to set property in run time.
Example:
The above block of code can be written in the following way too.
Caption
It sets the text displayed in the object's title bar or on the object.
Example:
Private Sub cmdSetTitle_Click()
[Link] = "New Program"
[Link] = "Hello"
[Link] = "New frame"
End Sub
'Caption' property of form sets the form's title text. The text to be displayed on label
is set.
Text
It sets the text in a TextBox.
Example:
[Link] = "New program"
Example:
Private Sub cmdChange_Click()
[Link] = 12000
[Link] = 7000
[Link] = 10000
[Link] = 12000
End Sub
Container
Moves an object into another container. You don't see it in the Properties Window,
it is a run-time only property.
Example:
Set [Link] = Frame1
Visible
Determines whether an object is visible or hidden.
Example:
[Link] = False
Enabled
Determines whether an object can respond to user generated events.
Example:
[Link]=False
Example:
[Link] = 0
[Link] = 1
[Link] = 2
When you press the TAB key, the focus will be given on Command3 first, then on Command2
and at last on Command1.
Control Box
Indicates whether a control-menu box is displayed on the form at run time. If this
property is set to False, the Close Button, Minimize Button and Maximize Button are not
shown on the form.
ShowInTaskBar
Determines whether the form appears in the windows taskbar.
Apart from them, there are many other controls provided by the Visual Basic
language which will be discussed in the appropriate chapters. You can add
external ActiveX controls that will enhance the interface and functionality of your
program.
Step 3: Click on Form and edit the caption property of the form. Write "My First VB
Program".
Step 4: Edit the caption property of the CommandButton from the Properties Window.
Write "Print".
Step 5: Double-Click the CommandButton to open the Code Window. Write the following
code.
Write code between the two lines 'Private Sub Command1_Click()' and 'End Sub'.
These two lines will be created automatically after double-clicking the
CommandButton.
Explanation
'Sub' means Sub-Routine or Sub-Procedure or Function. 'Command1_Click()' is
the sub-procedure name where 'Command1' is a control and 'Click' is an event.
'( )' this sign indicates that 'Command1_Click()' is a function. 'Private' is the
Scope. 'Print' is a Method.
You could also write [Link] where Form1 is an object and print is its method. „End
Sub indicates the end of the sub-procedure.
Press F5 to run the program or click the start icon button from the toolbar. The
code will be executed and the string "Welcome to [Link]" will be
displayed on the form as shown in the picture below.
Writing comments
Comments are the lines of text that are not executed but used for the advantage
of the programmers. Comments are written so that the other programmers can
easily understand your program and you can better understand the code in case
that it becomes complex or 16px. When you write comments, it becomes easy to
maintain the code of your application. Commenting is a part of Documentation
and it is a good practice to write comments.
The Name property of a control is very important as it helps you identify the
control in the code. Every control has the Name property. When you create a
control, Visual Basic sets the default Name property like Text1, Command1,
Form1 etc. It is suggested to use some specific prefixes for the Name property
especially when you'll use the controls in your code. This is a good programming
habit to modify the name so that it expresses or identifies a particular control with
the meaningful name. See the table below for the three-letter prefixes that you
will use for the naming purpose.
Controls Controls
Prefix Prefix
CommandButton
dir
OptionButton opt DirListBox
CheckBox
Line lin
ComboBox cbo
ListBox
lst
Shape shp
Timer
ole
tmr OLE
fra
Frame Form frm
Say there is a TextBox control that shows the result, set the Name property to
txtResult, a meaningful name. There is no need to edit the Name properties of all
the controls in your project because naming all the controls (if there are so
many) is time consuming. Name those controls using the prefixes which you use
in the code. If it is convenient to use the default Name properties for some
controls, there's no need to rename using the prefixes.
In fine, naming a control using a three-letter prefix is a good habit but only then when
the particular control is used in the code and this naming convention will certainly
increase the readability of your code, which is a great advantage.
Remember, there is no hard and fast naming rules. This is just a suggestion from
Microsoft. In fact, this is your personal preference, you may prefix the name of a
control in whatever way you want.
When you click, press a key, move the mouse or fire other events, the
particular block of code of the corresponding event procedure is executed, and then
the program behaves in a certain way. This is called event-driven programming.
When you fire an event, the code in the event procedure is executed, and then
visual basic performs its operations as per the instructions written in the event
procedure code. For example, in the first sample program, when you click the
'Print' button, the click event is fired, and then the code in the click event
procedure gets executed. The code tells Visual Basic to print a text on the form. So
as a result, you see a text printed on the form.
Example:
Write the following code in the DblClick event procedure of the form.
Output:
When you double-click on the form, the DblClick event procedure of the Form
object is invoked, and then the code in the DblClick event procedure is executed.
Thus, the code instructs Visual Basic to print a text on the form.
Unit II
Variables and Data Types
This VB6 lesson clarifies the concepts of variables and data types with
examples. Some simple definitions and explanations have given here. Hope
they will help you understand quickly and easily.
Variable
Variable is used to store value. The value of the variable may vary during the
program execution.
Constant
Constant is a fixed value that does not change during the program
execution. You can define your own constant to use it in your program.
Data Types
Visual Basic is rich in its data types. Data types are used to declare the
variables. At the time of declaration, memory is allocated for the variables.
Different data types are used to store different types of values.
Data Type
Storage Data Type Storage
String (variable-
Byte 1 byte length) Length + 10 bytes
String (Fixed-
Boolean 2 bytes Length of string
Length)
Byte 0 to 255
Boolean True/False
String (Variable
length) 0 to approximately 2 billion characters
-922,337,203,685,477.5808 to
Currency
922,337,203,685,477.5807
+,-79,228,162,514,264,337,593,543,950,335 if no
decimal is used
Decimal
+,-7.9228162514264337593543950335 (28 decimal
places)
Variable Declaration
Depending on where the variables are declared and how they are declared, there
are many ways to declare a variable in visual basic. When you declare a
variable, memory space for the variable is reserved. This is called memory
allocation. Different amount of memory space is reserved for different data
types.
Syntax:
Example:
End Sub
You can declare many variables in one line as follows and assign multiple variables
in one line using ':' operator.
End Sub
Example:
Dim num
Or,
Dim num As Variant
Or, if you choose not to declare a variable then also it is of the Variant data type.
So you can use a variable in Visual Basic without declaring it. The variant data
type can store numeric, date/time or string values. This is called implicit
declaration. That means, you are declaring the variable implicitly. But it is not
recommended to use implicit declaration and a good programmer will declare the
variables explicitly. Because, it can lead to errors that may not be detected at run
time.
Example:
area = pi * r * r
Print area
End Sub
Output: 12.5663704
Scope of variables:
Scope of variables determines which part of the code can access the variable. A
variable is declared in the general declaration section of a module to make it available
to all the procedures in the module.
Concepts of procedures and modules are necessary before jumping on the scope
part. So procedures and modules are clarified first.
What is a procedure?
Procedure is a particular block of code. Examine the following example.
Example:
The following block of code is a procedure.
Types of procedures
There are three types of procedures - sub procedure, function procedure and
property procedure.
Module
Visual Basic uses modules. Three kinds of modules are there - form modules, standard
modules, and class modules.
Example:
Syntax:
Example:
Static m As Integer
Static variables are declared inside a procedure. The static variables retain their values
even when a procedure ends but their scope is the procedure itself.
Example:
Note: You cannot declare a public variable inside a procedure. Public variables are
declared only within the general declarations section of a module.
Example:
'Form1
'In the form's declaration section
Public n As Integer
Meanings
Operators Operators Meanings
* Multiplication = equal to
Example: x=a+b
'=' , '+' are the operators.
x,a,b are the operands and 'a+b' is an expression. x=a+b is a statement.
Output: 20
Example:
Private Sub cmdDivision_Click()
Dim a As Double, b As Double, c As Double a = 12: b = 5 c=a\b Print c
End Sub
Output: 2
Example:
Private Sub cmdShow_Click()
Dim remainder As Integer, num As Integer
num = 21
remainder = num Mod 10
Print remainder
End Sub
Output: 1
Example:
Private Sub Command1_Click()
Dim a As Integer
a = Val([Link])
a=a+1
[Link] = a
End Sub
In the above program, Input is taken using Text1 and output is shown in Text2, where
output is the incremented value of the input.
Example:
Private Sub cmdShow_Click()
MsgBox "Hello, welcome to [Link]", _
vbInformation, "Welcome"
End Sub
In some cases, Visual Basic does it for you. That means that you don‟t need to
write code to convert the data types; conversion is done automatically. But this
doesn‟t happen all the time, so you need to learn how to convert them.
In the following example, Visual Basic implicitly converts the value of number to string
before assigning to msg.
Example:
Explicit conversion
In many cases you have to explicitly convert the data values to another data type.
Visual Basic has provided so many useful conversion functions.
Output: 6
Conversion functions
The functions are CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr,
and CVar. Val and Str functions are also used.
CStr
The Cstr function converts an expression to a string. This is useful when you‟re
displaying some numeric values in a text box control.
Example:
Dim v1 As Double
[Link] = CStr(v1)
Str
The Str function converts a number to a string. It is similar to the Cstr function.
Example:
CDbl
The CDbl function converts an expression into a Double. It also extracts the numeric
value from a string.
Example: If you omit the CDbl function, the program will raise an overflow error.
Example:
Example:
Val
Sometimes you can use the Val function instead of the CDbl function. Val
function returns a Double value. It only returns the numeric value contained in a
string. Unlike the CDbl function, it cannot convert a numeric expression.
Example:
Dim l As Double
l = Val([Link])
CInt
The CInt function converts a number to integer.
Example:
CLng
The CLng function converts to Long type.
Example:
Dim ln As Long
ln = CLng(1147483647.87656) 'Rounds up the value
[Link] ln
CBool
The CBool function converts an expression to Boolean Data type, i.e either True
or False. The value of zero is converted to False and all other numeric values are
converted to True. The strings <True= and <False= return True and False Boolean
values respectively.
Example:
Dim B as Boolean
B=cbool(0) 'Returns False
B=cbool(1) 'Returns true
B=cbool(345) 'Returns True
Control Structure
Prgrams are not monolithic sets of commands that carry out the sdame
calculationa every time they are executed. Instead, they adjust their behavior
depending on the data supplied or based on the result of a test condition. Visual
basic 6.0 provides three-control flow, or decision, structuires to take a course of
action depending on the outcome pf the test. They are:
IF … Then
If … Then … Else
Select Case
IF Blocks in VB6.0
The If control flow blocks provide a great way for decision making where one or more
statements are executed depending upon a condition.
If-Then
In case of If-Then block, the condition is first checked. The condition can either
be True or False. If it is True, the statements inside the If-Then block is
executed. Otherwise, it does not execute the code in the If-Then block, the
IfThen structure is skipped. It starts executing the statements just after the 'End
if' phrase.
Syntax:
If Condition Then
statements
End If
If a > 0 Then b = 1: c = 2
If-Else
An If-Else block has two parts. If the condition is True then the first part is
executed, otherwise the control goes to the second part and starts executing the
lines of statements in the second part of the If-Else block.
Syntax:
If Condition Then
statements1 Else
statements2
End If
Output: 50
Nested If-Else
If you have programmed in other languages, you might probably know about
nested if-else control flow block. In VB it is the same concept. See the syntax
and the examples to capture the concept.
In nested if-else, the structure is little changed, little advanced better to say,
from the simple If-Block. Here if the first condition does not satisfy, it looks
for the next condition preceded by the ElseIf term, if that too does not
satisfy, it looks for the next, and it goes on until the end of the structure.
Syntax:
If Condition Then
statements ElseIf
Condition then
statements ElseIf
Condition Then
statements
.......................
......................
Else
statements
End If
Example:
a = Val(InputBox("Enter a no."))
If a > 0 Then
Print "Positive"
ElseIf a < 0 Then
Print "Negative"
Else
Print "Zero"
End If
In a nested if-else block, one If-Block can reside in another. See the example
below.
Example:
If a > 0 Then
Print "Positive"
If a > 2 Then
Print "Greater than 2"
Else
Print "Less than 2"
End If
Else
If a < 0 Then
Print "Negative"
End If End
If
Example:
The Select Case block provides an efficient way for decision making which is
used to execute one block of statement(s) among a list of statement blocks
according to the determined value of an expression. The expression is preceded
by the "Select Case" phrase. The choices are made based on the value of this
expression
Syntax:
Example:
Case 0
Print "You have entered zero"
Case 1
Print "You have entered one"
Case 2
Print "You have entered two"
Case Else
Print "The number you entered is greater than 2"
End Select
One block of statement(s) will be executed depending upon the value of num. If
num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.
See the other forms of Select Case Structure in the following programs.
Example:
Example:
Do Loops
Loops are used to execute a block of statements repeatedly based on a condition.
i) Do While...Loop ii)
Do...Loop While iii)
Do...Loop Until.
The repeated execution of the statements inside the loop goes on as long as the
condition is true. When the condition becomes False, it exits the loop.
Syntax:
Do While Condition
statement(s)
Loop
The program first checks the condition. If num is less than 10, the statements
inside the Do While...Loop are executed. Again, the condition is checked. If it is
True, the statements are executed. In this way, the iterative execution goes on.
When the value of num becomes 10, the loop ends.
This loop structure first executes the statements and after that tests the condition
for the repeated execution.
Syntax:
Do
statement(s)
Another example: Though the condition does not satisfy, the program will print 11
as this loop structure first executes the statements and after that tests the condition.
Print num
num = num + 1
Loop While num <
10
Output: 11
The Do...Loop Untill structure executes the statements repeatedly until the
condition is met. It is an infinite loop if the condition does not satisfy. In this
case, the program cannot be stopped. Press Ctrl+Break key combination to
force it to stop. The loop continues until the condition is met. The repeated
execution of the statements stops when the condition is met.
Syntax:
Do
statement(s) Loop
Until Condition
Example:
'x is incremented until x becomes greater than 10
Dim x As Integer
x = 0 Do
x=x+1
Loop Until x > 10
MsgBox x
For...Next Loops
For...Next loop structure is useful when a block of statements are to be executed for
unknown number of times. But if a block of statements are to be executed for specified
number of times then a For … Next loop is better choice. Unlike a Do loop, a For loop uses
a variable called a counter that increases or deceases in value during each repetition of the
loop.
Syntax
Statements
Next [counter]
The argument counter, start, end, and increment are all numeric. The increment
argument can be either positive or negative If increment is positive, start must
be less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body
of the loop to execute. If Step isn‟t set, then increment defaults to 1.
Dim i As Integer
For i = 0 To 10
Print i
Next i
Dim i As Integer
For i = 0 To 6 Step 2
Print i
Next i
Output:
0
2
4
6
Example: To print in descending order from 10 to 0 in step of -3.
Dim i As Integer
For i = 10 To 0 Step -3
Print i
Next i
Output:
10
7
4
1
Syntax
Statements
Next element
Dim i As Integer
For i = 0 To 10
If i = 3 Then
Exit For
End If
Print i
Next i
Output:
0
1
2
If num = 4 Then
Exit Do
End If
Loop
Output:
0
12
3
Example:
Private Sub Command1_Click()
If [Link] = True Then
Print "Option1 is ON"
Else
Print "Option1 is OFF"
End If
End Sub
Output:
Example:
Output:
Example:
Output:
Example: The previous program can also be written in the following way.
Output:
If [Link] = 1 Then
Print "Coffee"
End If
If [Link] = 1 Then
Print "Pizza"
End If
If [Link] = 1 Then
Print "Chocolate"
End If
End Sub
Output:
Syntax:
Select Case expression
Case value0
statements Case
value1
statements Case
value2
statements ...........
...............
Case else
statements
End select
Example:
Dim num As Integer
num = Val([Link])
Select Case num
Case 0
Print "You have entered zero"
Case 1
Print "You have entered one"
Case 2
Print "You have entered two"
Case Else
Print "The number you entered is greater than 2"
End Select
One block of statement(s) will be executed depending upon the value of num. If
num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be
evaluated.
See the other forms of Select Case Structure in the following programs.
Example:
Dim score As Integer
score = Val([Link])
Select Case score
Case 900 To 1000
Print "First position"
Case 800 To 899
Print "Second position"
Case 700 To 799
Print "Third position"
Case Else
Print "No position, try again"
End Select
Example:
Dim num As Integer
num = Val([Link])
Select Case num
Case Is > 0
Example:
Select Case value
Case 0, 1, 2, 3, 4, 5
Print "The values are 0,1,2,3,4,5"
Case Else
Print "Other values"
End Select
Declaring an array
Syntax: Dim Variable_Name(index) As [Type]
Example:
Dim month(10) As Integer '11 elements
'or
Dim month(1 to 12) as Integer '12 elements
Types of array
The array used in the example is a one-dimensional and fixed-size array. An
array can have more than one dimension. The other types of arrays are
multidimensional arrays, Dynamic arrays and Control arrays.
Fixed-Size Array: We know the total number of items the array in the above
example holds. So that is a Fixed-Size array.
Example:
MsgBox "Lower bound = " & a & " Upper bound = " & b
End Sub
Initializing an array
You can use For Loop to initialize an array.
Example:
Dim day(10) As Integer, i As Integer
For i = 0 To 10
day(i) = InputBox("Enter day value")
Next i
You can also initialize each array item separately in the way a variable is
initialized.
Example: This program inputs the Sale amount of each day and sums the total
amount of 5 days.
For i = 1 To 5
SaleDay(i) = InputBox("Enter Sale amount of Day " & i)
Sale = Sale + SaleDay(i)
Next i
End Sub
Multi-Dimensional Arrays:
An array can be multi-dimensional that means, it can have more than one
dimension. A list of data is represented in a one-dimensional array where a
multi-dimensional array represents a table of data. An array can be two
dimensional, three dimensional and so on. We generally don't need an array of
more than two dimensions, it is enough to use one and two dimensional arrays.
You can use a higher dimensional array when the program is too complex. A
two dimensional array takes the row-column form.
Declaration:
Dim value(5, 5) As Integer 'two dimensional
'Or,
Dim value(1 to 5, 1 to 5) As Double
Dim number(6, 9, 8) As Integer 'three dimensinoal
Initialization:
To initialize the array elements, you first need to recognize the array elements.
For example, the array 'value(2, 2)' has 9 elements. They are value(0,0),
value(0,1),value(0,2), value(1,0), value(1,1), value(1,2), value(2,0 ),
value(2,1), value(2,2). For the initialization, you may wish to use For Loop or
initialize each element like variables. Using For Loop is a better choice as it
reduces the number of lines of code. But sometimes, separately initializing each
element like a variable is much more convenient. And it also depends on the
type of program you are writing.
'initializiation of matrix1
matrix1(0, 0) = Val([Link])
matrix1(0, 1) = Val([Link])
matrix1(1, 0) = Val([Link])
matrix1(1, 1) = Val([Link])
'initializiation of matrix2
matrix2(0, 0) = Val([Link])
matrix2(0, 1) = Val([Link])
matrix2(1, 0) = Val([Link])
matrix2(1, 1) = Val([Link])
Next j
Print ""
Next i
End Sub
Static array
Basically, you can create either static or dynamic arrays. Static arrays must
include a fixed number of items, and this number must be known at compile time
so that the compiler can set aside the necessary amount of memory. You create
a static array using a Dim statement with a constant argument:
Visual Basic starts indexing the array with 0. Therefore, the preceding array
actually holds 101 items.
Most programs don't use static arrays because programmers rarely know at
compile time how many items you need and also because static arrays can't be
resized during execution. Both these issues are solved by dynamic arrays. You
declare and create dynamic arrays in two distinct steps. In general, you declare
the array to account for its visibility (for example, at the beginning of a module if
you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you
actually need it, using a ReDim statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0,
unless an Option Base 1 statement is placed at the beginning of the module. My
suggestion is this: Never use an Option Base statement because it makes code
reuse more difficult. (You can't cut and paste routines without worrying about the
current Option Base.) If you want to explicitly use a lower index different from 0,
use this syntax instead:
Dynamic Array
In case of a fixed size array, we have seen that the size of the array is fixed or
unchanged, but there may be some situations where you may want to change the
array size. A dynamic arraycan be resized at run time whenever you want.
Example:
Note: Unlike the Dim and Static statements, the ReDim statements are
executable. So a ReDim statement can only be in a procedure and when you
execute the ReDim statement, all the values stored in the array are lost. You can
use the ReDim statement repeatedly to change the array size.
Example:
For i = 0 To 2
arr(i) = InputBox("Enter the value")
Next i
Output: If the input values through InputBox are 5,6,7 then the following will be
printed on the form.
5 6 7 9
Example: In this example, 32 and 54 are passed to the function 'sum' from
Form_Load procedure.
'Function Definition
Private Function sum(n1 As Integer, n2 As Integer) 'n1, n2 are 'parameters
[Link] = n1 + n2
End Function
________________________________________________________________
__
Private Sub Form_Load()
[Link] = ""
'Function callgin
Call sum(32, 54) '32 and 54 are arguments
End Sub
Output:
'Function Definition
Private Function sum(n1 As Integer, n2 As Integer) As Integer
'Returns a value
sum = n1 + n2
End Function
____________________________________________________________
Private Sub Form_Load()
[Link] = ""
'Function calling and assigning the returned value
[Link] = sum(60, 40)
End Sub
While passing the arguments by reference, references of the variables are passed.
So if the argument is passed by reference, it can be modified by the called
procedure and the original value of the argument in the calling procedure will be
changed. But the argument value will be unchanged if you call the procedure
using constants or expressions as parameters.
Example:
'Calling procedure
Private Sub Command1_Click()
Dim a As Integer 'The value of a is 0 after declaration
Call num(a)
x=x+1
End Function
On the other hand, when the arguments are passed by value, the actual values
are passed. So the called procedure cannot change their original values in any
way.
Example:
'Calling procedure
Private Sub Command1_Click()
Dim a As Integer 'The value of a is 0 after declaration
Call num(a)
Control Array
Till now we have discussed array of variables. Similarly you can also have an array
of controls by grouping a set of controls together. The controls must be of the
same type like all TextBoxes or all CommandButtons.
Or, after placing a control on the form, copy that and paste on the form. It
will create control array for you.
2. Set the Index property of each control or you may not change as it is
automatically set.
3. Now its done. You are ready to use the control array in your code.
For i = 0 To 4
Command1(i).BackColor = vbBlue
Next i
End Sub
You can also pass a value to the Index parameter from other procedures.
Control array is useful when you want to clear a set of TextBox fields. Create a
control array of 5 TextBox controls and write the following code in the Click event
procedure of a CommandButton control.
Example:
Output:
Example:
Text1(2).Visible = True
End Sub
The first thing that you may want to do with the ListBox control is to add items
or elements to it. You have two options for that. You can either add items in
design-time or in run-time.
Example:
Private Sub Form_Load()
[Link] "England" End
Sub
Here List1 is the ListBox name.
Output:
Syntax:
[Link] n
n is the index of an item. The Index starts from 0, so the index of the second
item is 1.
Example: This program will delete the 1st item from ListBox.
Private Sub Form_Load()
[Link] 0
End Sub
Example:
Example:
Private Sub Form_Load()
[Link]
Print [Link]
End Sub
Output:
Example:
Private Sub Form_Load()
[Link]
[Link] "England"
[Link] "USA" [Link]
"Germany"
[Link]
Print
End Sub
Output: 2
Example:
Private Sub cmdShow_Click()
Print [Link]
End Sub
___________________________________________________________
Private Sub Form_Load() [Link] "England"
[Link] "USA" [Link] "Germany"
End Sub
Output:
Example:
Private Sub Form_Load() [Link]
[Link] "England"
[Link] "USA" [Link]
"Germany"
[Link](0)
Print
End Sub
Output: England
Example:
Private Sub Command1_Click()
Print [Link]
End Sub
_______________________________________________________________
Private Sub Form_Load()
[Link] "England"
[Link] "USA"
[Link] "Germany"
End Sub
Output:
ComboBox
ComboBox is the combination of a TextBox and a ListBox. The user can type in
the text field to select an item or select an item manually from the list. All the
properties, events and methods of a ComboBox control are as same as the ListBox
control. So the discussion of ListBox control in previous lessons also applies for
ComboBox control.
Styles of ComboBox
There are three styles of ComboBox controls-- Dropdown Combo, Simple Combo
and Dropdown List. You can change/select the style from the Style property of
ComboBox.
Example:
Timer Control
Timer control is used to execute lines of code at specific intervals. Using this
control, you can create animations without any knowledge of graphics or
animation. Though you cannot create some groundbreaking animations using
timer control, but it is sufficient for your application. You can create an
animated menu for your software. This control is not visible at runtime.
For example, set the Interval to 100 , to execute the code in the timer event
procedure every 100 milliseconds.
Example: Now place a Timer control and a CommandButton on the form. Set
its Enabled property to False and set the Interval property to 1.
Private Sub cmdStart_Click()
[Link] = True 'Enables the Timer
End Sub
________________________________________________________
Private Sub Timer1_Timer()
[Link] = [Link] + 1
End Sub
Now run the program and click on Start button to start the Timer. Once the Timer
is enabled, the code in the Timer procedure is executed every 1 millisecond and
it increases the width of the current form in the above program example.
InputBox
InputBox is a function that prompts for user-input. InputBox shows a dialog box
that inputs value from the user.
Syntax:
a=InputBox( promt, [Title], [Default], [xpos], [ypos])
where 'a' is a variable to which the value will be assigned. The texts inside the
InputBox are optional except the "prompt" text. "prompt" text is the prompt
message. "title" is the title of the message box window. "Default" is the default
value given by the programmer. 'xpos' and 'ypos' are the geometric positions with
respect to x and y axis respectively.
Note: Parameters in brackets are always optional. Do not write the brackets in
your program.
Example:
Private Sub cmdTakeInput_Click()
Dim n As Integer
n = InputBox("Enter the value of n : ")
Print n
End Sub
The above program prints the value of n taken from the InputBox function.
Dim n As Integer
n = InputBox("Enter the value of n : ", "Input", 5)
Print n
End Sub
MsgBox
The MsgBox function shows a dialog box displaying the output value or a
message.
Syntax:
MsgBox Prompt, [MsgBox style], [Title]
where Promt text is the prompt message, [MsgBox Style] is the msgbox style
constants and [Title] is the text displayed in the title bar of the MsgBox dialog.
Example:
Private Sub cmdShowMessage_Click()
Dim n As Integer
n = 10
MsgBox "The value of n is " & n
End Sub
Menu:
Windows applications provide groups of related commands in Menus. These
commands depend on the application, but some-such as Open and Save are
frequently found in applications.
Visual Basic provides an easy way to create menus with the modal Menu Editor
dialog. The below dialog is displayed when the Menu Editor is selected in the
Tool Menu. The Menu Editor command is grayed unless the form is visible. And
also you can display the Menu Editor window by right clicking on the Form and
selecting Menu Editor.
Basically, each menu item has a Caption property (possibly with an embedded
& character to create an access key) and a Name. Each item also exposes three
Boolean properties, Enabled, Visible, and Checked, which you can set both at
design time and at run time.
Building a menu is a simple. You enter the item's Caption and Name, set other
properties (or accept the default values for those properties), and press Enter to
move to the next item. When you want to create a submenu, you press the
Right Arrow button (or the Alt+R hot key). When you want to return to work on
top-level menus4those items that appear in the menu bar when the application
runs4you click the Left Arrow button (or press Alt+L). You can move items up
and down in the hierarchy by clicking the corresponding buttons or the hot keys
Alt+U and Alt+B, respectively.
You can create up to five levels of submenus (six including the menu bar),
which are too many even for the most patient user. If you find yourself working
with more than three menu levels, think about trashing your specifications and
redesigning your application from the ground up.
You can insert a separator bar using the hypen (-) character for the Caption
property. But even these separator items must be assigned a unique value for
the Name property, which is a real nuisance. If you forget to enter a menu
item's Name, the Menu Editor complains when you decide to close it. The
convention used in this book is that all menu names begin with the three
letters mnu.
An expanded Menu Editor window.
An expanded menu
The programmer can create menu control arrays. The Index TextBox specifies
the menu's index in the control array.
The Menu Editor dialog also provides several CheckBoxes to control the
appearance of the Menu.
Checked : This is unchecked by default and allows the programmer the option
of creating a checked menu item( a menu item that act as a toggle and displays
a check mark when selected. The following is a Check Menu items.
To add commands to the Form's menu bar, enter a caption and a name for each
command. As soon as you start typing the command's caption, it also appears
in a new line in the list at the bottom of the Menu Editor window. To add more
commands click Enter and type the Caption and the Name.
Creating Menus
Open a new Project and save the form as [Link] and save the project as
[Link].
Choose Tools ››› Menu Editor and type the menu items as shown below.
Caption
Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
Initialize
The Initialize event is the first event of a form when the program runs. This
event is raised even before the actual form window is created. You can use this
event to initialize form‟s properties.
Example:
Load
After the Initialize event, Load event fires when the Form is loaded in the
memory. This Form event is invoked for assigning values to a control's property
and for initializing variables.
Note that the form is not visible yet. For this reason, you cannot invoke a
graphic function like Cls, PSet, Point, Circle, Line etc and you cannot give the
focus to any control with the SetFocus method in the form's Load event
procedure. The Print command will not even work.
On the other hand, this won't be a problem setting a control's property in the
form's load event.
Example:
Private Sub Form_Load()
[Link] = ""
[Link] = ""
var1 = 0 End Sub
Resize
After the Load event, the form receives the Resize event. The form's Resize event
is also raised when you resize the form either manually or programmatically.
Another important form event is the Paint event which I'll not discuss here. Paint
event will be covered later in another lesson.
Note that when you run your program, form events such as Initialize, Load, Resize,
Activate and Paint events are raised automatically one by one. The Paint event is
not raised when the form's AutoRedraw property is set to True.
QueryUnload
When you close or unload the form, the form first receives the QueryUnload event
and then the Unload event.
The QueryUnload event is invoked when the form is about to be closed. When the
form is closed, it may be unloaded by the user, the task manager, the code, owner
form, MDI form or it may be closed when the current windows session is ending.
This event procedure takes two parameters, Cancel and UnloadMode. The Cancel
parameter cancels the unload operation, and depending on the symbolic values of
UnloadMode, a particular task can be performed.
Example:
Symbolic constant values for the UnloadMode parameter are explained below:-
vbFormControlMenu: when the form is closed by the user.
• vbFormCode: Use this constant when you're closing a form by code.
• vbAppWindows: when the current windows session is ending.
• vbAppTaskManager: when the task manager is closing the application.
• vbFormMDIForm: when the MDI parent is closing the form.
• vbFormOwner: when the owner form is closing.
Unload
The Unload event fires when the Form unloads. You can use this event to warn the
user that data needs to be saved before closing the application.
Example: In this program, you cannot close the Form keeping the text field blank
Private Sub Form_Unload(Cancel As Integer)
If [Link] = "" Then
MsgBox "You cannot exit keeping the text field blank"
Cancel = True
End If End
Sub
When Cancel = True, you cannot close the Form. The Cancel parameter is used
to cancel the form's unload operation.
Project -> Add MDI form. Click Project from the menu bar, and click Add MDI
form. It's simple! Remember, a project can have only one MDI form.
These restrictions are there because MDI forms are the special type of forms,
especially used to handle multiple child forms.
• MDI child form: To add a child form, you have to add a regular form, and
set the MDIchild property to True. You can have many child forms and can
show an MDI child form using the Show method.
• AutoShowChildren property of an MDI form: The default value of the
AutoShowChildren property is True. When it is True, the MDI child forms
are displayed once they are loaded. When the value is False only then you
can keep it hidden after loading, otherwise not.
• Restrictions of the MDI child forms:
1. You can't display an MDI child form outside its parent.
2. You can't display a menu bar on the MDI child form.
Now coming to the point - how the MDI form works. The parent form contains a
menu bar on top of it. From there, the user opens or creates a new document. In
this way, the user accomplishes his/her work in one or multiple documents, then
saves and closes the document (form). You can create instances of a single form
in the code using the Set keyword (Using the object variables).
'Inside the MDIForm module
Private Sub mnuFileNew_Click()
Dim frm As New Form1
[Link] End
Sub
Note that '(ActiveForm Is Nothing)' represents that there is no active form. The
'Not' keyword before it negates the value.
• The rows in a database table are used to describe similar items. The rows are
referred to as database records. In general, no two rows in a database table
will be alike.
In this database table, each record represents a single individual. The fields
(descriptors of the individuals) include an identification number (ID No), Name,
Date of Birth, Height, and Weight.
Most databases use indexes to allow faster access to the information in the
database. Indexes are sorted lists that point to a particular row in a table. In the
example just seen, the ID No field could be used as an index.
A database using a single table is called a flat database. Most databases are
made up of many tables. When using multiple tables within a database, these
tables must have some common fields to allow cross-referencing of the tables.
The referral of one table to another via a common field is called a relation. Such
groupings of tables are called relational databases.
In our first example, we will use a sample database that comes with Visual
Basic. This database ([Link]) is found in the main Visual Basic directory (try
c:\Program Files\Microsoft Visual Studio\VB98). It is a database of books about
computers.
In Visual Basic 6.0, data access is accomplished using ActiveX Data Objects
(ADO). In Visual Basic 2008, data access is accomplished using [Link], which
is a part of the .NET Framework. There are a number of differences, both
conceptually and in terms of tasks, between the two technologies.
In Visual Basic 6.0, there are two common methods of implementing data access
in an application: at design time, by binding to an ADODC (ADO data control) or
The ADO (ActiveX Data Object) data control is the primary interface between a
Visual Basic application and a database. It can be used without writing any code
at all! Or, it can be a central part of a complex database management system.
This icon may not appear in your Visual Basic toolbox. If it doesn‟t, select Project
from the main menu, then click Components. The Components window will
appear. Select Microsoft ADO Data Control, then click OK. The control will be
added to your toolbox.
The data control (or tool) can access databases created by several other programs
besides Visual Basic (or Microsoft Access). Some other formats supported include
Btrieve, dBase, FoxPro, and Paradox databases.
1. Connect to a database.
2. Open a specified database table.
3. Create a virtual table based on a database query.
4. Pass database fields to other Visual Basic tools, for display or editing. Such
tools are bound tools (controls), or data aware.
5. Add new records or update a database.
6. Trap any errors that may occur while accessing data.
7. Close the database.
LockType indicates the type of locks placed on records during editing (default
setting makes databases read-only).
RecordSource Determines the table (or virtual table) the data control is
attached to.
• As a rule, you need one data control for every database table, or virtual table,
you need access to. One row of a table is accessible to each data control at
any one time. This is referred to as the current record.
• When a data control is placed on a form, it appears with the assigned caption
and four arrow buttons:
The arrows are used to navigate through the table rows (records). As indicated,
the buttons can be used to move to the beginning of the table, the end of the
table, or from record to record.
• If your database does not have a data link, you need to create one. This
process is best illustrated by example. We will be using
the [Link] in our first example, so these steps show you how to
create its data link:
Most of the Visual Basic tools we‟ve studied can be used as bound, or
dataaware, tools (or controls). That means, certain tool properties can be tied
to a particular database field. To use a bound control, one or more data controls
must be on the form.
Text Box - Can be used to provide read/write access to a specified text data
field. Probably, the most widely used data bound tool.
Combo Box - Can be used to provide read/write access to a text data field.
List Box - Can be used to provide read/write access to a text data field.
Picture Box - Used to display a graphical image from a bitmap, icon, or metafile
on your form. Provides read/write access to a image/binary data field.
Image Box - Used to display a graphical image from a bitmap, icon, or metafile
on your form (uses fewer resources than a picture box). Provides read/write
access to a image/binary data field.
• There are also three „custom‟ data aware tools, the DataCombo (better than
using the bound combo box), DataList (better than the bound list box), and
DataGrid tools, we will look at later.
If the data in a data-aware control is changed and then the user changes focus
to another control or tool, the database will automatically be updated with the
new data (assuming LockType is set to allow an update).
• To make using bound controls easy, follow these steps (in order listed) in
placing the controls on a form:
1. Draw the bound control on the same form as the data control to
which it will be bound.
2. Set the DataSource property. Click on the drop-down arrow to list
the data controls on your form. Choose one.
3. Set the DataField property. Click on the drop-down arrow to list the
fields associated with the selected data control records. Make your
choice.
4. Set all other properties, as required.
By following these steps in order, we avoid potential data access errors.
• The relationships between the bound data control and the data control are:
STEPS:
1. Open a new Visual Basic project.
2. Put a data control (an intrinsic control, located in the VB toolbox) on the
form and set the properties as follows:
Property Value
(Name) datAuthors
DatabaseName ..\[Link]
Notes: When you use the Data Control in a project, the properties that
must be set are Database Name and Record Source, in that
order. DatabaseName is the name of the database you want to use, and the
RecordSource is the name of the table in that database that you want to
use.
3. In your form, create a text box for each field in the Authors table, with labels.
(If you were to open the database in Access, you would see that the three fields
of the Authors table are Au_ID, Author, and Year Born.) Set the properties of the
three textboxes as follows:
When you want a control (such as a text box) to display data from a
database, the properties that must be set are DataSource and Datafield.
The DataSource is the name of the data control on the form (it should
already be configured), and the DataField is the name of the particular
field in the database that should be displayed in the control (this field will
be in the table that was chosen for the RecordSource of the data control).
4. Save and run the project. Use the arrows on the data control to scroll
through the data.
5. On any record, change the data in the author name or year born field. Move
ahead, then move back to the record you changed. Note that your changes
remain in effect. The data control automatically updates a record when you
move off of the record.
EXERCISE 2
Using Navigation Buttons with a Data Control
4. Put the following four lines of code in the appropriate Click events for the
buttons:
Event Code
cmdMoveNext_Click [Link]
cmdMoveLast_Click [Link]
cmdMovePrevious_Click [Link]
cmdMoveFirst_Click [Link]
6. Move to the last record and then click the Move Next button twice.
EXERCISE 3
STEPS:
1. Copy the files from Exercise #2 into a new folder and open the VBP file in
the new folder.
2. When the user clicks on the MoveNext button, and there is no next record,
your code should stay on the same record (the last one).
[Link] If
[Link] = True Then
[Link]
End If
FYI: Instead of [Link], you could use MoveFirst to let the user loop
around to the first record.
3. Double clicking the OLE control on your form will activate the object‟s
application. Visual Basic also allows you to activate the object from your
code.A Insert dialogbox is [Link] are two option create new or create
from [Link] select it as you want .
6. Creating a Excel chart will allow you to access the Excel application to
define the chart.
[Link] your application. Double click on the OLE control and use it in your
project as you want.
2. Select Create from File and use the Browse button to find the Word document
4. This Word document page has been sized so that it will fit onto a form.
Change the SizeMode property of the OLE control to Stretch.
5. Run your application. Double click the OLE control to see that Word is
activated with the selected document opened.