0% found this document useful (0 votes)
60 views

Visual Basic: The Learning Edition

This document discusses Visual Basic and its different editions, project types, and integrated development environment. It then provides details on VB procedures including sub procedures, functions, and property procedures. It also covers some string functions in VB like String$() and Instr().

Uploaded by

Ajinkya Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Visual Basic: The Learning Edition

This document discusses Visual Basic and its different editions, project types, and integrated development environment. It then provides details on VB procedures including sub procedures, functions, and property procedures. It also covers some string functions in VB like String$() and Instr().

Uploaded by

Ajinkya Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 22

Notes by – Mr. Chandratre Y. V.

Visual Basic

There are 3 different editions of Visual Basic.


1) The Learning Edition :
This is the most basic edition. This edition allows us to write many different types of programs,
but lacks a number of tools that the editions have.
2) The Professional Edition :
This edition is designed for professionals. This edition contains all that the Learning Edition
contains and more, such as the capability to write Active-X controls and documents.
3) The Enterprise Edition :
This is the complete VB edition. This edition is targeted towards professional programmers
who may work in a team and includes additional tools such as Visual SourceSafe, a version-
control system that coordinates team programming.

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.

 String Functions : In VB, these functions are worked on Strings.


1) String$() :
This function returns a string, which contains specific number of characters.
e.g. Private Sub cmdstring_click ()
Form1.cls
Form1.Print String$(20, “*”)
Form1.Print String$(20,”A”)
End Sub
When above code is executed, the first String$() function will return a string
of “*” character whose length is 20. On the form user will see 20 “*” characters.
Similarly second String$() function will display a string consisting “A” character 20
times.

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.

Constant Value Description


vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in string to uppercase.
Viz. ans = strconv(“Visual Basic, 2)

 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)

3) Sin(), Cos(), Tan() :


These are trigonometric functions in VB.
Sin() : The Sin() returns sine of an angle supplied to it as an argument.
Cos() : Returns cosine of an angle.
Tan() : Returns tangent of an angle supplied to it as an argument.
The general syntax is
Sin(dblAngle)
Cos(dblAngle)
Tan(dblAngle)
E.g.
Dim dblSinResult as double
Dim dblCosResult as Double
Dim dblTanResult as Double
dblSinResult = Sin(4.93)
dblCosResult = Cos(4.93)
dblTanResult = Tan(4.93)
The above code will find Sin(), Cos(), Tan() value of the angle supplied to
the respective functions as an argument. It must be noted that you must supply the
Notes by – Mr. Chandratre Y. V.

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.

 Date & Time Functions :


1) Now() :
This retrieves the date and time. E.g.
MsgBox “The current date and time is at this instance” &Now
The above statement will display the system date and time in the message
box. We can also print the current date and time on the form, for this you have to
write the following statements.
Form1.print “The current date and time is :” & Now

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.

Date datatype. The syntax is TimeValue(Timestring). The example of valid time


string are,
5 : 10
5:10:25
18:05
5:10 PM
4:05 AM

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

10)Month, Day and Year():


These are used to retrieve an integer value representing the month, day or
year respectively. The general syntax is as –
Month(expression$)
Day(expression$)
Year(expression$) Where expression$ is a Date variable.
Eg.
Private Sub Command1_Click()
Form1.Print Month(Now)
Form1.Print Day(Now)
Form1.Print Year(Now)
End Sub
Here, assume if date is 12/25/2001, the output of above code will be 12, 25
& 2001.

 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.

Form Caption Count No. of Characters


Label Caption Enter the String
Label Caption No. of chars
Label Name lblResult
Caption “”
Command Button Name cmdCount
Caption Count
Text Box Name txtString
Text “”
The code will be as below.
‘ This is general Declaration
Option Explicit
Private Sub cmdCount_Click()
Dim I as Integer
Dim Count as integer
Dim s as string
S = Trim(txtString.Text)
For I = 1 To Len(S)
If (Mid(S, I, 1) <> “ “) Then
‘increment Count if character is found
count = count + 1
End If
Next i
‘ Display the count in lblResult label
lblResult = count
End Sub.

 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.

Playing with String

Txtfirst

Txtmiddle

Txtlast

txtinitials

Private Sub txtinitials_keypress(key ascii as integer)


Dim first as string
Dim middle as string
Notes by – Mr. Chandratre Y. V.

Dim last as string


First = left(txtfirst,1) + “.”
Middle = left(txtmiddle, 1) + “.”
Last = left(txtlast, 1) + “.”
Txtinitials.text = first &middle &last
Endsub

 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

o IF and IIF Statements :


IF statement is used to redirect program flow based on results of a
conditional test. IF statement can be of two forms. Single line and multilane. The
syntax for single line IF statement is
IF <cond> Then <statement>
Here, <cond> can be any expression that evaluates to a True or False
value. True is defined as any nonzero number such as –10, 1, 50, 100 etc. False
on the other hand is zero (0).
Viz. IF txtName.Text = “ “ Then MsgBox “You must enter your name”
In above example, if txtName is empty i.e. user has not entered any data,
then the message will be displayed, which informs user that he should enter some
data in txtName.
The syntax of multilane IF statement is as-
IF <cond> Then
<statement 1>
<statement 2>
.
.
.
<statement n>
End If
Viz. Private Sub Command1_Click()
If txtName.Text = “” Then MsgBox “Enter Your Name Please !”
TxtName.SetFocus
End If
End Sub
The IF statement also allows to add an Else Clause. The statement written
in Else Clause will be executed if the condition specified in the IF statement
evaluates to False. The syntax of IF statement along with Else Clause is
Notes by – Mr. Chandratre Y. V.

IF <cond> Then
<statement>
Else
<statement>
End If

Viz. Private Sub comdSex_Click()


If OptMale.Value = True Then
MsgBox “Employee is Male”
Else
MsgBox “Employee is Female”
End If
End Sub
In some cases we need to check more than one condition. Each condition is
checked until a True condition is found. To handle such type of things we use Else IF
Clause. Once the True condition is found the code within the block between the Else If
and next Else If or End If statement is executed.
Following is the syntax of Else If Clause
If <condition1> Then
<statement block 1>
[ElseIf] <condition 2> then
<statement block 2>
[Else]
<statement block 3>
End If
Here first condition1 will be checked, if it is true, then directly statement in block
1 will be executed. If condition 1 is False, condition 2 will be checked if it is found true,
then statement in block 2 will be executed. If both condition 1 and condition 2
evaluates to False, statements in block 3 will be executed.
Viz.
Private Sub Command1_Click()
If val (Text1.Text) < 10 Then
MsgBox “It is a Single Digit Number”
ElseIf Val(Text1.Text) < 100 Then
MsgBox “It is a Two Digit Number”
ElseIf val(Text1.Text) < 1000 Then
MsgBox “It is a Three Digit Number”
Else
MsgBox “The value is more than three digits.”
End If
End Sub

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.

o Select Case Statement :


This statement is used for checking multiple conditions. The syntax of
Select Case statement is as –
Select Case <Expression>
Case <Expression List1>
<statement Block1>
Case <Expression List2>
<statement Block2>
Case Else
<statement Block>
End Select
Viz.
Select Case txtGrade,Text
Case “A”
lblAnnounce.Caption = “Perfect”
Case “B”
lblAnnounce.Caption = “Great”
Case “C”
lblAnnounce.Caption = “Study Harder”
Case “D”
lblAnnounce.Caption = “Get Help !”
Case “E”
lblAnnounce.Caption = “Back to Basics”
Case Else
lblAnnounce.Caption = “Error in Grade”
End Select
Example of another form of Case statement
Select txtGames.Text
Case “Cricket”, “FootBall”, “Hockey”
MsgBox “You have selected an outdoor game”
Case “”Chess”, “Carrom”, “Computer Games”
MsgBox “You have selected indoor game”
End Select
Note that Select Case format does not support the inclusion of logical
operators so cannot use ANS, OR, XOR, NOT for Select Cases test expression.
Notes by – Mr. Chandratre Y. V.

 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>

Viz. Private Sub cmdLoopWhile_Click()


Dim Mycounter as integer
Mycounter = 1
Do
Form1.Print Mycounter
Mycounter = mycounter + 1
Loop While (Mycounter <= 10)
End Sub
This will print the out as 1 to 10 numbers.

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 For … Next Statement :


To use this construct you have to use a counter. You will always loop from
some starting value to some end value. By default For … Next loop always
increments by one every time through the loop. The format of For Statement is as_
For IntCounter = Instart To IntEnd
[Step Int Increment]
Block of one or more VB Statements
Next [IntCounter]
To do first iteration intCounter is initialized to inStart value. When execution
reaches to Next statement it will increment the value of intCounter by 1 and control
will again go to first statement if the value of intStart is less than intend, second
iteration will occur and so on. By default if you do not write the step it will
increment intCounter by 1.
Viz. For IntCounter = 1 to 5
Form1.Print IntCounter
Next
Viz. For IntCounter = 0 to 10 step 2
Form1. Print IntCounter
Next

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

o While … End With :


This is used in a case where we are operating on one object. Viz. consider
following code while setting the various properties of Form1 object.
Form1.Top = 0
Form1.Left = 0
Form1.Windowstate = Vbmaximized
Form1.Caption = “With … End with example !”
Form1.Show
So instead of writing Form1 again and again in above VB statements we
can also do this using With … End With construct as_
With Form1.
.Top = 0
.Left = 0
.WindowState = VbMaximized
.Caption = “With … End With Example”
.Show
End With

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.

Modal and Non-modal dialog boxes :


A modal dialog box does not allow the user to continue with other part of application,
unless it is closed or unloaded, whereas Non-modal or modeless dialog box allows
shifting of focus between the dialog box and another form without closing the dialog box.
MsgBox and InputBox are the best examples of modal dialog boxes. Where as tool box,
properties window, Project Explorer are the best examples of modeless dialog boxes.
Messgage Box :
It is predefined modal dialog box. MsgBox can be used as both a statement and function.
The MsgBox has five arguments we can pass to it.
The message to display
The icon button to display in the dialog box
The title for the dialog box.
The help file’s name
The format or syntax of MsgBox() is
Int Response = MsgBox (strMessage [, int style], [strTitle])
The first paramenter is the actual message, which is displayed on it. The second parameter decides
an icon and the button on the Message Box. The following table shows the constants which are
used to display an icon on the message box.
Notes by – Mr. Chandratre Y. V.

Constant Icon displayed Icon


vbCritical Critical Message icon
vbQuestion Warning Query Message icon
vbExclamation Warning Message icon
vbInformation Information Message icon

Following is the list of constants for buttons on the MsgBox.


Button constant Description
vbOKonly Display the OK button, this is the default button
vbOKCancel Display OK and Cancel button on MsgBox.
vbYesNo Displays Yes and No buttons on Msg Box.
vbYesNoCancel Displays Yes, No and Cancel buttons
vbRetryCancel Display Retry and Cancel buttons
vbAbortRetryCancel DisplayAbort, Retry, Cancel buttons
vbMsgBoxHelpButton Adds the Help button on the MsgBox.

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 –

Input Box () Function :


This can be used to take or retrieve the data from a user. The MsgBox displays data or
information on to the user where as Input box takes data from the user. An input box is a
message box with a text filed in which user can type the value. In Input dialog box unlike
MsgBox we have only two buttons. OK and Cancel. User can move MsgBox or InputBox
but cannot resize it. Also unlike MsgBox you do not have a way to place an icon on Input
box. The format of the InputBox() function is
strAnswer = InputBox (strPrompt [strTitle] [, strDefault] [, intxpos] [, intYpos] )
where,
strprompt :- The message may be a Question that appears in the InputBox.
strtitle :- The text which appears in the title bar of the InputBox.
strDefault :- A default value that appears in the input box’s input field i.e. in the text box.
Notes by – Mr. Chandratre Y. V.

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_

You might also like