Visual Basic: The Learning Edition
Visual Basic: The Learning Edition
Visual Basic
When we start VB, it brings up the New Project Dialog box, as shown below.
In this, we see some of the project types
that VB supports :
Standard Window EXE programs
Active EXE files
ActiveX DLLs
ActiveX controls
Programs written by the VB
App.Wizard
Data projects
IIS (Internet Information Server)
app.
Visual Basic add-ins
ActiveX document DLLs
ActiveX document EXE files
DHTML applications
VB Enterprose Edition controls
Here we just want to take a look at the basics of Standard Visual Basic project, so
double click it. This will open Visual Basic itself as shown below. Following figure shows the
Visual Basic Integrated Development Environment (IDE). The IDE is where you do your
programming work in Visual Basic.
The Visual Basic IDE has three distinct states – Design, Run and Debug. The current
state appears in VB’s title bar. The IDE is composed of following parts :
1) The Menu Bar 2) The toolbar
3) The Project Explorer 4) The Properties window
5) The Form Layout window 6) The toolbox
7) Form designers 8) Code windows
Notes by – Mr. Chandratre Y. V.
Title Bar
Menubar
Toolbar
Project
Explorer
Toolbox
Properties
Window
Form
Designer
Form
Layout
Window
Notes by – Mr. Chandratre Y. V.
Functions :
Visual Basic program can be broken into logical components called
procedures. Procedures are useful for condensing repeated operations such as
frequently used calculations, text and control manipulation etc.
o Procedure :
Procedures are nothing but small logical components. When your
application needs a task to execute repeatedly you will put it in a procedure and
each time when you need to execute the task you will give a call to that procedure
to accomplish the task.
The benefits of procedures in programming are –
1. It is easier to debug the program with procedures, which breaks a program into
discrete logical limits.
2. Procedures used in one program can act as building block for other programs
with slight modification.
A procedure in VB can be of following types
a) Sub procedures b) Function c) Property procedure
a) Sub Procedures :
A Sub procedure can be placed in standard, class and form modules. Each
time the procedure is called the statements between Sub and End Sub are
executed. The syntax for Sub procedure is as follows-
[Private / Public] Sub < procedurename>
[(arglist)]
[Statements]
End Sub
Here, Arglist is a list of argument names separated by comma. Each
argument acts like variable in the procedure. The keyword, Private or Public
decides the scope of variable.
The Sub Procedure can be of two types.
1) Event Procedures :
An event procedure is a procedure block whose name is decided by VB.
Name of event procedure is the concatenation of controls actual name, an
underscore ( _ ) and the event name. The following is an example of event
procedure
Private Sub Form1_Locad ()
Form1.left = 0
Form1.Top = 0
End Sub
In this example, Form1 is the name of the form. Load is an event of the
form and that is why we have “Form1_Load” as the name of the event
procedure. During loading of Form1, the code written in the event procedure,
Form1_Load will get executed.
Notes by – Mr. Chandratre Y. V.
2) General Procedure :
General procedures are user-defined procedures. Following code is the
example of general procedures.
Public Sub GetTotal()
‘This procedure calculates the total
‘amount of purchased items.
Dim curtotal as currency
Curtotal = val(txtItem1.text) + val(txtitem2.text) + val(txtItem3.text)
TxtTotal.text = curtotal
End Sub
Sub procedure does not return any value it is simple a code, which gets
executed when you give a call to it. After completion of execution the control 1
returns back the calling procedure.
Calling Procedures :
To call a procedure or funtion from another procedure or function, simply
put the name of the procedure, eg. To call GetTotal() procedure we will write
–
GetTotal ()
The above statement will call the GetTotal procedure or you can put a
keyword call in front of the name of the procedure. This helps you
distinguish that it is a call to a procedure and not just a VB statement.
b) Function :
A function is simply a procedure that returns one value to the routine that
calls it. It is just like a Sub procedure, Sub procedure is a subroutine, which cannot
return value.
Functions can be used to perform certain calculations, tasks like verification
and checks on strings entered by the user in the Text Boxes.
The return value from a function may be any valid data type, an array, a
user-defined type or an object. Similar to sub procedures Functions can be used
with Public or Private keywords.
Creating a Function :
‘function’ keyword is used to create a Function. You may choose private or
public keywords to define the scope of the function. You also need to give the
function a datatype that it will return. To do this As keyword is used after the name
of the function. In the code of the function, at the end you have to set the name of
the function equal to the value you want to return.
Eg. Private Function Employee_Display() As String
Dim strName As String
StrName = Text1.Text
Employee_Display = strName
End Function
Notes by – Mr. Chandratre Y. V.
c) Property Procedure :
A property procedure is used to create and manipulate custom properties.
Property Procedure creates read only properties to forms, standard modules or
class modules.
There are three types of property procedures.
1) Property Let Procedure – Sets the information in a Private variable
2) Property Get procedure – Returns information about a Private variable
3) Property Set procedure – Can be used to set the reference to an object.
2) Instr() :
This returns the location where one string resides in another string. Means
Instr() finds the sub string from the given string.
e.g. Private Sub comdInstr_click()
Dim strName = “Hello World”
Form1.cls
Form1.Print Instr(strName, “ello”)
End Sub
Here first argument of Instr() function is a string in which you want to
search. The next argument of Instr() is a string you want to search for. Instr()
function returns the numeric location of 2nd parameter located within first string.
3) InstrRev() :
This function returns the location of one string residing in another from the
end of the string.
Private Sub cmdInstrRev_click()
Dim strName = “Hello World”
Form1.cls
Form1.Print InstrRev(strName, “Hello”)
End Sub
This will display the output as “olleH”
Notes by – Mr. Chandratre Y. V.
4) Left$() :
This returns a string containing a specified number of character from the left
side of a string. e.g.
Private Sub cmdLeft_Click()
Dim strName as String
StrName = “Hello World”
Form1.cls
Form1.Print Left$(strName “5”)
End Sub
This will print “Hello” on the form.
5) Right$() :
This returns a string containing specified number of characters from the
right side of a string. e.g.
Private Sub cmdRight_Click()
Form1.cls
Form1.Print (“Hello World”,11)
Form1.Print Right$ (“Hello World”, 5)
End Sub
This will give the output as “Hello World” “World” on the form.
6) Mid$()
This function returns a substring of a specified number of characters within
a string. E.g.
Private Sub cmdMid_Click()
Form1.cls
Form1.Print Mid$ (“Hello World”, 1,5)
End Sub
The output will be “Hello”
7) Len ()
This function returns the length of the string. E.g.
Private Sub cmdLen_Click()
Form1.cls
Form1.Print Len (“Hello”)
End Sub
The output will be 5, which a length of “Hello” strings.
8) Replace()
This function allows replacing a character or characters in a string with
another character (or characters). E.g.
Private Sub cmdReplace_Click()
Form1.cls
Replace(strName, “5.0”, 6.0”)
Notes by – Mr. Chandratre Y. V.
Form1.Print strName
End Sub
The output will be a string “Visual Basic 6.0”
9) Trim$()
Removes both leading and trailing spaces from a string. E.g.
Form1.Print Trim$ (“ Hello World ”)
The output will be “Hello World” on the form.
10)Rtrim$()
Removes trailing spaces from a string. E.g.
Form1.Print Rtrim$ (“ Hello World”)
The output will be “Hello World” on the form.
11)Ltrim$()
Removes leading spaces from a string. E.g.
Form1.Print Ltrim$ (“Hello World ”)
The output will be “Hello World” on the form.
12)Str$()
Returns a string from a numeric expression. E.g.
SntNumber = Str$(100)
This will return “100” and store into StrNumber, which is a string variable.
13)Format$()
This function returns a string in a specified format. You can pass date, time,
Number or string to this function along with specific format in which you want the
resultant string. E.g.
Form1.Print Format$ (50, “Currency”)
Form1.Print Format$(0, “Yes/No”)
14)UCase()
This function returns its string argument all in uppercase letters.
15)LCase()
This function returns its string argument all in lowercase letters.
16)strconv ()
This function works with argument in upper and lower case. The syntax of
strconv is as
Strconv (strexpr, conversion)
Where strexpr is the string expression to be converted and conversion is
the values specifying the type of conversion to perform. The 3 conversion
argument settings for strconv function are –
Notes by – Mr. Chandratre Y. V.
Mathematical Functions :
1) Abs() :
This function returns the absolute value of a number. The general syntax is
Abs (numExpression)
The Abs() function returns the unsigned value of the supplied numerical
expression. E.g.
Abs(250) and Abs(-250) both will return the value 250.
2) Atn() :
This returns the arctangent of a numerical expression which is supplied as a
argument Atn() function. The general syntax is
Atn (dbiExpression)
Here dbiExpression is an expression for which you want arctangent. E.g.
Dim dblAngle as double
Dim dblRatio as Double
dbiAngle = Atn(dbiRatio)
angle in Radians and not in Degrees. If the angle is in degrees you must first
convert it into radians, before using above functions. To convert angle given in
degrees to radians use following formula.
Radians = Degrees * PI / 180
4) Hex Functions :
This function returns a string that represents the value of numerical
expression in hexadecimal format. The syntax for this function is as
Hex(numExpression)
Viz. Dim A as Integer
Dim B as String
A = 140
B = Hex(A)
This will show the output as “8C”. Hexadecimal is often used to display
Memory addresses.
If numExpression which is an argument to the Hex function is an integer,
then the value returned by Hex Function is string of 4 or fewer bytes. Otherwise
the returned string can be up to 8 bytes.
5) Oct Functions :
Oct() function returns a variant or string, which is Octal format of the
supplied numerical expression. The syntax is as
Oct (numExpression)
Viz. Consider strOctal as a string variable and we have follo. statement.
Dim strOctal as string
strOctal = Oct(100)
If the numExpression, is an argument to the Oct function, is an integer, then
the value returned by Oct functions is a string of 4 or fewer bytes. Otherwise it can
be upto 11 bytes.
6) Sqr Function :
This function calculates the square root of a number. The syntax is as
Sqr (dblExpression)
For Example, Dim dblResult as double
DbiResult = sqr(64)
7) Val Function :
Val function returns the numeric value of the supplied string expression. The
syntax is as
Val (strExpression)
For example, Dim A as double, B as double
A = val(“2342”
B = val(“ 2342”)
This will assign a value 2342 to A and B variables.
Notes by – Mr. Chandratre Y. V.
2) Date() / Date$() :
The Date function returns a variant of type date, where as Date$ function
returns string in the mm-dd-yy format. E.g.
Private sub cmdDate_click()
Form1.Print “Date = “ &Date
Form1.Print “Date = “ &Date$
EndSub
The output of the above code will be a current system date, it may be
12/30/01 and 12-30-2001
3) Time() / Time$() :
The Time function returns the current system time as a date datatype and
Time$ function returns the current system Time as a string. E.g.
Private sub cmdTime_click()
Form1.Print “Current time is = “ &Time
Form1.Print “Current time is = “ &Time$
EndSub
The output of the above code will be 7:40:51 AM and 7:40:51
4) DatePart():
This function is used to return the specific part of a date variable. From a
given date, it can return day, month, year and so on. E.g.
Private sub cmdDatePart_click()
Form1.Print DatePart (“m”, now)
Form1.Print DatePart (“d”, now)
Form1.Print DatePart (“yyyy”, now)
EndSub
So, DatePart() function takes 2 arguments, first argument to DatePart() is
the string which specifies which part you want to retrieve. The second argument is
a valid Date/Time variable.
The various time period values with which Date Arithmetic function works
are listed below.
Internal Vale Time Period
yyyy Year
Q Quarter
Notes by – Mr. Chandratre Y. V.
M Month
Y Day of Year
D Day
W Weekday (Sunday 1, Monday 2 ….)
WW Week
H Hour
N Minute
S Second
5) DateAdd():
This function returns a date after adding or subtracting a specified time
interval to another date. E.g.
Private sub cmdDateAdd_click()
Dim dtDate as date
Form1.cls
dtDate = Now()
Form1.Print dtDate
Form1.Print DateAdd(“d”, 90, dtDate)
End Sub
DateAdd function takes 3 arguments. The first argument specifies which
part you want to operate (d mean days). Second argument specifies how many
units you want to add to the third argument and the third argument is a valid date/
time variable.
6) DateDiff():
This function calculates specified interval of time between two dates. E.g. If
you want to calculate number of Days between 2 dates, it will be as
Form1.Print (“d”, dtDate1, dtDate2)
The second and third arguments are the two dates and the first argument is
a string, which specifies the interval. The meaning of above statement is that the
user wants the difference between dtDate1, dtDate2 in terms of number of days.
7) DateValue():
This function is used to convert string data type into a date data type. The
syntax is DateValue (dtstring). Here dtstring is a string, which is to be converted
into Date datatype. The values which are valid for dtstring are…
01/01/1994
May 1, 2000
19-Jan-2001
19 January 01
8) TimeValue():
This function converts a time, specified in the form of string into a Date
datatype. TimeValue function converts a time, specified in the form of string into a
Notes by – Mr. Chandratre Y. V.
9) DateSerial():
This function converts the numeric values of an indicated date to a VB date
Data type. The syntax is DateSerial (Year, Month, date).
Year : It is a number or expression that evaluates between 100 and 9999
inclusive.
Month : It is a number of expression that evaluates between 1 and 12 inclusive.
Day : It is a number or expression that evaluates between 1 and 31 inclusive.
Following is an example
Private Sub Command1_Click ()
ThisYear = val(Text1.Text)
This month = val(Text2.Text)
Thisday = val(Text3.Text)
On Error GoTo BadDate
NewDate = DateSerial(this year, thismonth, thisday)
Exit Sub
MsgBox “Invalid Date”
End Sub
Program 1: Write a program to count no of characters in the given string. (Do not
count spaces).
Design the form as per following.
Control Property Value
Notes by – Mr. Chandratre Y. V.
Program 2: Write a program to entering a name in the form of First Name, Middle
Name and Last Name and print the initials.
Design the form as below.
Txtfirst
Txtmiddle
Txtlast
txtinitials
Control Statements :
The VB supports control statements such as
If … Then … Else
Select … Case
and loop structure statements such as
Do While … loop
Do Lopp While
For … Next method
IF <cond> Then
<statement>
Else
<statement>
End If
o IIF() function :
This function allows the user to combine IF…Then …Else statement into
one line. This function accepts three parameters. The first parameter is the
condition, if it evaluates to True the value of the second parameter is returned. If
Notes by – Mr. Chandratre Y. V.
the first parameter evaluates to False, the value of the third parameter is returned.
The syntax of IIF() function is as-
IIF(<condition is True> <Return exp1> <Else Return exp2>)
Viz. Private Sub condMax_Click()
Dim as integer B as Integer, Imax as Integer
A = 10, B = 20
Imax = IIF (A<B, B,A)
MsgBox “The Maximum of two numbers is “ & Imax
End Sub.
What is looping ?
A loop is a series of one of more statements that executes more than one
time. Loop statement repeats until a certain predefined condition is not meet. Two
types of loop structures are available in VB. The Do … Loop and For … Next lop.
The Do … Loop construct offers many variations and is used typically if you do not
know how many iterations will be performed.
Following are the various forms or formats of Do…Loop construct.
1) Do While
2) While … Wend
3) Loop … While
4) Do Until
5) Loop … Until
1) Do While :
Do while tests the loop condition each time through the loop and it
keeps executing while the test expression is a True value. Do while is always
terminated with Loop statement. The general syntax of Do While is as
Do While <cond>
Statements>
Loop
If the condition at the top of the loop is True value then the statements
between Do and Loop are executed.
If the condition evaluates to false then there will not be execution of
statements between Do and Loop.
Viz. Private Sub cmdDoWhile_Click()
Dim intNumber as Integer
IntNumber = 10
Do while intnumber < 100
Lblnumber.caption = intnumber
Intnumber = intnumber + 10
Loop
End Sub
The above program will change lblNumber’s Caption from 10 to 20, 20
to 30 and so on till 90.
2) While … Wend :
This construct was not used any more. This construct was used in
previous versions of Basic Language. The syntax of the statement is
While <cond>
<statements>
Wend
The example of While … Wend is _
Private Sub cmdCont_Click()
Dim Mycounter as integer
Mycounter = 1
While mycounter <= 10
Notes by – Mr. Chandratre Y. V.
Fom1.Print mycounter
Mycounter = mycounter + 1
Wend
End Sub
This will give the output as 1 to 10 numbers.
3) Loop While :
In this we have to check the condition at the bottom. So using constructs
it is a guarantee that at least once the code written between Loop and While
will be executed. The syntax of this statement is as-
Do
<statement>
Loop While <condition>
4) Do Until :
This loop is similar to Do While loop, except you are executing the loop
until a condition becomes True. The syntax of this statement is
Do Until <cond>
<statement>
Loop
Viz.
Private Sub cmdUntil_Click()
Dim Mycounter as Integer
Mycounter = 1
Do Until Mycounter = 10
Form1.Print Mycounter
Mycounter = Mycounter + 1
Loop
End Sub
This code will give the output as 1 to 10.
5) Loop Until :
This construct is same as Do Until except it checks the condition at the
end of the loop. This construct is similar to Loop While except, you are
executing until condition becomes true. The statement inside the loop will be
executed at least once. The syntax is as _
Do
Notes by – Mr. Chandratre Y. V.
<Statement Block>
Loop until <condition>
Viz. Private Sub Form_Load()
Do
X = Input Box (“Password Please?”)
Loop Until X = “Password”
End Sub
The code will display Input box where you have to enter the password, if
you enter other than “Password” you have to enter it again. This will continue
until you enter “Password”.
o Exit Statement :
Some times depending on the data you may want to terminate an event or
other kinds of procedures early. In that case to break the function or loop, you can
use Exit statement. The syntax for Exit statement is
Exit Sub | Function | Do | For
The vertical bars between the keywords indicate that only one of those
keywords follow Exit. To exit from Sub procedure you use the Exit Sub, To exit
from Function procedure you use the Exit Function.
Viz. Consider a program which checks sales, if it is more than 5000 then only it
will calculate the Bonus.
Private Sub cmdcalculateBonus_Click()
If (txtSales.Text < 5000.00)
Exit Sub
Else
Notes by – Mr. Chandratre Y. V.
TxtBonus.Text = TxtSales.Text*0.05
End If
End Sub
Dialog Boxes :
Dialog Boxes are those windows, which can use any time, whenever you want to present
some information or to prompt the user. Dialog boxes can be of three types. They are –
1) Predefined Dialog Boxes : e.g. Input Box, Message Box
2) Custom Dialog Boxes : Created by adding some controls to form
3) Standard Dialog Boxes : Created using Common dialog control.
The third parameter decides the title, which appears on Title bar of the MsgBox. The
fourth and fifth parameter is about Help. The fourth parameter indicates or specifies the
name of the Helpfile, which will be displayed when user clicks HelpBotton.
Following are the examples of MsgBox. If you write
MsgBox “Hello World”, vbExclamation, “Hello”. The output will be –
If you wite
MsgBox (“Save the data?”, vbQuestion+vbYesNo,”Save”). The output will be –
intXpos, intYpos :- These are X and Y positions when you want to display input box, if you
do not specify these, VB displays InputBox at the center of the screen.
The returned value of InputBox is the data entered in the Text Filed of Input Box, and it is
of variant type. You can interpret the returned value of InputBox as string.
Following is the example –
strAnswer = InputBox [“Enter the Name”, “Get Name”,Bill Gates”, 500, 750)
This will display the output as_