VB Notes Ug
VB Notes Ug
Before we begin Visual Basic 6 programming, let us understand some basic concepts of
programming. According to Webopedia, a computer program is an organized list of instructions
that, when executed, causes the computer to behave in a predetermined manner. Without
programs, computers are useless. Therefore, programming means designing or creating a set of
instructions to ask the computer to carry out certain jobs which normally are very much faster
than human beings can do.
A lot of people think that computer CPU is a very intelligent thing, which in actual fact it
is a dumb and inanimate object that can do nothing without human assistance. The microchips
of a CPU can only understand two distinct electrical states, namely, the on and off states, or 0
and 1 codes in the binary system. So, the CPU only understands the combination of 0 and 1 code,
a language which we called machine language. Machine language is extremely difficult to learn
and it is not for us laymen to master it easily. Fortunately, we have many smart programmers
who wrote interpreters and compilers that can translate human language-like programs such as
BASIC into machine language so that the computer can carry out the instructions entered by the
users. Machine language is known as the primitive language while Interpreters and compilers
like Visual Basic are called high-level language. Some of the high level computer languages
beside Visual Basic are Fortran, Cobol, Java, C, C++, Turbo Pascal, and etc .
VISUAL BASIC
VISUAL BASIC is a high level programming language which evolved from the earlier
DOS version called BASIC.BASIC means Beginners' All-purpose Symbolic Instruction Code. It
is a very easy programming language to learn. The code looks a lot like English Language.
Different software companies produced different versions of BASIC, such as Microsoft
QBASIC, QUICKBASIC, GWBASIC, and IBM BASICA and so on. However, people prefer to
use Microsoft Visual Basic today, as it is a well developed programming language and
supporting resources are available everywhere. Now, there are many versions of VB exist in the
market, the most popular one and still widely used by many VB programmers is none other than
Visual Basic 6. We also have VB.net, VB2005, VB2008 and the latest VB2010. Both Vb2008
and VB2010 are fully object oriented programming (OOP) language.
VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main
divergence from the old BASIC. In BASIC, programming is done in a text-only environment and
the program is executed sequentially. In VB, programming is done in a graphical environment.
In the old BASIC, you have to write program code for each graphical object you wish to display
it on screen, including its position and its color. However, In VB, you just need to drag and drop
any graphical object anywhere on the form, and you can change its color any time using the
properties windows.
With VB 6, you can create any program depending on your objective. For example, if
you are a college or university lecturer, you can create educational programs to teach business,
economics, engineering, computer science, accountancy , financial management, information
system and more to make teaching more effective and interesting. If you are in business, you can
also create business programs such as inventory management system, point-of-sale system,
payroll system, financial program as well as accounting program to help manage your business
and increase productivity. For those of you who like games and working as games programmer,
you can create those programs as well. Indeed, there is no limit to what program you can create!
There are many such programs in this tutorial, so you must spend more time on the tutorial in
order to learn how to create those programs.
STEPS IN VB APPLICATIONS
Understanding the problem
Clearly define what the application is to do: purpose, inputs, processing, outputs.
Design screens
Visualize application running and design its user interface – sketch it on pape.r
Make a list of the controls needed, decide on their names, and write a description.
Build screens
Start Visual Studio and create forms and other controls
Test correctness
Attempt to run the application and correct syntax errors Repeatedly run the program with test data
as input and correct any run-time or logical errors.
Before you can program in VB 6, you need to install Visual Basic 6 in your computer.
You can choose to start a new project, open an existing project or select a list of recently opened
programs. A project is a collection of files that make up your application.
You'll notice that the IDE contains a main menu bar and several windows (toolbox, form,
project explorer, and properties). You can customize the IDE to some degree to work according
to your preferences, which I will address in the next section.
The VB6 IDE (which was first introduced in VB5, and has not significantly changed in
VB6) is by default, an MDI (Multiple Document Interface) application, where the various
windows are "docked" at certain locations of the screen and can interlock with each other (for
example, the project explorer and the properties window are initially interlocked with each
other). This arrangement looks nice and organized upon first glance, and many people do prefer
working with VB using this default setup, or are not aware of the alternatives.
In earlier versions of VB, the IDE was an SDI (Single Document Interface), where each
Of these windows (toolbox, form, project explorer, and properties window) would float
"independently" on the Windows desktop. I found it easy to move from window to window to
get to what I needed, and it was particularly easy to design the forms. With the VB5/VB6 default
setup, I feel "boxed in" when designing a form, and if you move one of the other windows (like
the Properties window), you may find that it will "re-dock" itself in an area of the screen that you
didn't expect, re-arranging all of the other windows – this I find frustrating. Fortunately, the IDE
can be customized to use an SDI arrangement as well as to set other preferences.
PROPERTIES WINDOW
This window allows us to change some of the properties associated with an object at design time.
Displays all the properties of the object (relating to the active project, userforms or control) that
can be changed at design time.
Lists the design-time properties for selected objects and their current settings. You can change
these properties at design time. When you select multiple controls, the Properties window
contains a list of the properties common to all the selected controls.
WindowElementsObjectBox Lists the currently selected object. Only objects from the active
form are visible. If you select multiple objects, the properties common to the objects and their
settings, based on the first object selected, appear on the Properties List tabs.
PropertiesListTabs Alphabetic Tab - Alphabetically lists all properties for the selected object
that can be changed at design time, as well as their current settings. You can change the property
setting by selecting the property name and typing or selecting the new setting.
Categorized Tab - Lists all properties for the selected object by category. For example,
BackColor, Caption, and ForeColor are in the Appearance category. You can collapse the list so
that you see the categories or you can expand a category to see the properties. When you expand
or collapse the list, you see a plus (+) icon or minus (-) icon to the left of the category name.
Form Layout window is a simple visual basic design tool whose purpose is to give the
user a thumbnail view of the current form. This helps in controlling the form position in the
Windows environment. When more number of forms are there in a particular program, this
―Form Layout‖ window is helpful to arrange all the forms onscreen, in exactly the way in which
the user needs them.
By simply dragging the miniature form to a particular location, the position of a form can be set
in the ―Form Layout‖ window.
Left and Top Properties
The screen location for form in Visual Basic can be set at design time using the Left and Top
properties in the ― Properties‖ window. These properties can also be set programmatically.
StartUpPosition Property
Visual Basic supports a property named ― StartUpPosition‖ which allows Windows to select a
location automatically. The Left and Top properties are taken by default.
CODE WINDOW
This displays the code associated with the item selected in the Project Explorer window.
Also sometimes referred to as a Module window.
You can even just double click the item in the Project Explorer window.
Displaying the Code Window
To display the code select the item in the Project Explorer window and either choose (View >
Code) or you can alternatively use the shortcut key (F7).
A code module will normally contain more than one procedure or function.
The IDE offers you a choice of whether to display the procedures one at a time (procedure view)
or all at one (full module view).
You can change the views by clicking on the small buttons in the lower-left corner of the code
window. Full Module view is the default.
You can minimise, maximise, hide and rearrange your code windows.
The main characteristic of a Form is the title bar on which the Form's caption is
displayed. On the left end of the title bar is the Control Menu icon. Clicking this icon opens the
Control Menu. Maximize, Minimize and Close buttons can be found on the right side of the
Form. Clicking on these buttons performs the associated function.
The following figure illustrates the appearance of a Form
By default, Visual Basic suggests the name of the first Form created when the project started.
Loading and Unloading Forms
In order to load and unload the forms, Load and Unload statements are used. The Load statement
has the following syntax :
Load FormName
And the Unload statement has the following syntax :
Unload FormName
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show
method which cares of both loading and displaying the Form, the load statement doesn't show the
Form. You have to call the Form's Show method to display it on the desktop.
Showing and Hiding Forms
Show method is used to Show a Form. If the Form is loaded but invisible, the Show method is
used to bring the Form on Top every other window. If the Form is not loaded, the Show method
loads it and then displays it.
Syntax of the Show method of the Form
FormName.Show modeThe Formname
variable is the Form's name, and the
optional argument mode determines
whether the Form will be Modal or not.
It can have one of the following
syntax:
0-Modeless (default)
1-Modal
Modeless Forms are the normal Forms. Modeless Forms interact with the user and the user
allowed to switch to any other Form of the application. If you do not specify the optional mode
argument, by default the mode is set to modeless.
The Modal Forms takes the total control of the application where user cannot switch to any other
Forms in the application unless the Form is closed. A modal Form, thus, must have a Close
button or some means to close the Form in order to return to the Form where the Modal Form
was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
You must understand that the Forms that are hidden are not unloaded ; they remains in the
memory and can be displayed instantly with the Show Method. When a Form is hidden, you can
still access its properties and code. For instance, you can change the settings of its Control
Properties or call any Public functions in the Form.
The following is an example illustrates the Show method and Mode statement
Open a new Project and save the Project
Design the application as shown below
Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2
Caption Form3
Form
Name frm3
Click on a
Caption
button to display
Label
Name
a Form
Label1
The following code is typed in the Click event of the command buttons
Run the application. Clicking on the buttons will display the Forms respectively. But you can see
that in the cmd2_Click( ) event additionally VbModal argument has been added. You can see the
difference after you display the forms by clicking on the command buttons.
Finding out the difference between Unload and Hide method
To know what the difference is between Unload and Hide methods we will do an example. Open
a new project and save the project. Draw two buttons on the form and name those as shown
above.
In the click event of the Hide button Following code is entered. Me.Hide
In the click event of the Unload button following code is entered.
Unload Me
Save the project and run the application. Once you click on Hide button you can note that the
Form is invisible but the application is still running. But when you click on Unload button you
can see that the application is terminated.
Visual Basic 6.0- Properties, Methods And Events
All the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects
have associated properties, methods and events.
Real world objects are loaded with properties. For example, a flower is loaded certain color,
shape and fragrance. Similarly programming objects are loaded with properties. A property is a
named attribute of a programming object. Properties define the characteristics of an object such
as Size, Color etc. or sometimes the way in which it behaves. For example, a TextBox accepts
properties such as Enabled, Font, MultiLine, Text, Visible, Width, etc.
Enables property allows the TextBox to be enabled or disabled at run time depending on the
condition set to True or False.
Font property sets a particular font in the TextBox.
MultiLine property allows the TextBox to accept and display multiple lines at run time.
Text property of the TextBox control sets a particular text in the control.
Visible property is used to hide the object at run time.
Width property sets the TextBox to the desired width at design time.
The properties that are discussed above are design-time properties that can be set at the design
time by selecting the Properties Window. But certain properties cannot be set at design time. For
example, the CurrentX and CurrentY properties of a Form cannot be set at the design time.
A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. A complete definition
of cat must only encompass on its looks, but should also include a complete itemization of its
activities. Therefore, a cat's methods might be move, jump, play, breath etc.
Similarly in object-oriented programming, a method is a connected or built-in procedure, a
block of code that can be invoked to impart some action on a particular object. A method requires an object to
provide them with a context. For example, the word Move has no meaning in Visual Basic, but the statement,
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence
like system generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of
events. An event is an action that calls a function or may cause another event. Event handlers are
functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
Mouse events
Keyboard events
Mouse-Based Events
Mouse events occur when the mouse makes any movement in controls or the forms. The following are some
ii. MouseDown
This event gets triggered when the mouse button is pressed and the cursor is brought towards the downside of
it.
iii. MouseUp
This event gets triggered when the mouse pointer is over the control which is handling it and the already
iv. MouseLeave
This is the event that gets triggered when the mouse pointer leaves the control.
v. MouseWheel
This event gets triggered when the wheel of the mouse moves and the control is provided the focus.
includes actions such as keypress, keydown, enter, etc. Let us study some of the keyboard-based events in
detail.
i. KeyDown
This event is a keyboard-based trigger that occurs when a key is pressed towards the downside and the control
has focus.
ii. KeyUp
This event is a keyboard-based trigger that occurs when a key is pressed towards the upside and the control
has focus.
iii. KeyPress
This event gets triggered when a particular key is pressed onto the keyboard.
VARIABLES
A variable is simply a name you give to an area of memory in which a data value used by your
program is stored. When you need to retrieve that data, or modify its value, you can refer to the
memory location by the variable's name.
The final character can be a "type-declaration character". Only some of the variable types can use
them, as shown below:
Use of type-declaration characters in VB is not encouraged; the modern style is to use the "As"
clause in a data declaration statement (described below).
VB is not case-sensitive: PAY, Pay and pay all refer to the same variable. If you type a
variable on a line in a case other than the case you used when you declared the variable, VB will
change the case to match that of the declared variable when you leave that line.
As long as you stick to the rules above, VB is "happy"; however, many programmers follow
stylistic naming conventions in an effort to improve the readability of their code. The naming
conventions involve using a one-to-four character lower-case prefix to start off the name. The
purpose of the prefix is to identify the data type of the variable (like "int" for integers and "str"
for strings). These naming conventions are sometimes called "Hungarian naming conventions"
(after Charles Simonyi, an early Microsoft programmer – and Hungarian native – who proposed
the conventions). Two other prominent programmers, Leszynski and Reddick, also have led the
charge for naming conventions.
The chart below shows each variable type, a recommended three-character prefix, and a
sample variable name:
Declaration Levels
A local variable is one that is declared within a procedure. A member variable is a member of a
Visual Basic type; it is declared at module level, inside a class, structure, or module, but not
within any procedure internal to that class, structure, or module.
Shared and Instance Variables
In a class or structure, the category of a member variable depends on whether or not it is shared.
If it is declared with the Shared keyword, it is a shared variable, and it exists in a single copy
shared among all instances of the class or structure.
Otherwise it is an instance variable, and a separate copy of it is created for each instance of the
class or structure. A given copy of an instance variable is available only to the instance for which
it was created. It is independent of a copy in any other instance.
DATA TYPE
The As clause in the declaration statement allows you to define the data type or object
type of the variable you are declaring. You can specify any of the following types for a variable:
An elementary data type, such as Boolean, Long, or Decimal
A composite data type, such as an array or structure
An object type, or class, defined either in your application or in another application
A .NET Framework class, such as Label or TextBox
An interface type, such as IComparable or IDisposable
Object Object (class) 4 bytes on 32- Any type can be stored in a variable of type
Objec
bit platform
8 bytes on 64-
bit platform
Note that you use one of five keywords to declare a variable; which one you use depends on
the scope you want the variable to have. There are three levels of scope:
project-level (also called "global" or "application" scope; the variable is accessible to all
procedures in all modules of the project)
module-level (the variable is accessible to all procedures in the module in which it is declared)
The General Declarations Section of a form or standard module. This section of a module is not
labeled as such; it simply exists at the beginning of a code module, after the "Option Explicit"
statement but prior to the first Sub or Function procedure. Declaring a variable here makes it a
project-level variable (if the Public or Global keyword is used) or a module-level variable (if the
Private or Dim keyword is used).
Within a Sub or Function procedure. Declaring a variable here makes it a local-level variable; only
the Dim or Static keyword can be used here. The recommended practice is to declare all local
variables within a procedure immediately following the Sub or Function header and prior to any
executable statements (although VB will allow you to declare variables anywhere within the
procedure).
The following table shows how the five different declarative keywords and the location
of their declaration affects the scope:
Keyword Where
General Declarations General Sub or Function procedure of
Used to Declared
Section of a Form Declarations a Form or Standard Module
Declare the
(.frm) Module Section of a
Variable:
Standard (.bas)
Module
Dim (preferred keyword module-level scope module-level local-level scope (value of the
for local-, but not module- scope variable is NOT preserved
level variables) between calls
Static not allowed not allowed local-level scope (value of the
variable is preserved between
calls)
Private (preferred keyword module-level scope module-level not allowed
for module-level variables) scope
project-level scope
Public (but references to the project-level scope not allowed
variable must be
qualified with the
form name; also there
are some minor
restrictions on the
types of variables that
can be declared as
public in a form)
Global (the use of this
keyword is discouraged; it not allowed project-level scope not allowed
CONSTANTS
VB supports the use of symbolic, or named constants. Constants are similar to variables,
except that you provide a value for the constant when you declare it, and its value can never
change. The syntax for declaring a constant is:
A global (project-level) constant can only be declared in a standard (.bas) module (not a form),
using "Public Const" or "Global Const" (the "Public" keyword is preferred). Module-level
constants can be declared in the General Declarations Section of either a standard or form code
module using "Private Const" (or just "Const"; the default is "Private"). Local-level constants are
declared in any procedure of a standard or form module just using the word "Const" (no "Public"
or "Private"). If you omit the "As datatype" clause, VB will use its "best guess" as to what the
datatype should be, based on the expression.
A constant is a meaningful name that takes the place of a number or string that does not change.
Constants store values that, as the name implies, remain constant throughout the execution of an
application. You can use constants that are defined by the controls or components you work with, or
you can create your own. Constants you create yourself are described as user-defined.
You declare a constant with the Const statement, using the same guidelines you would for creating a
variable name.
A Const statement's scope is the same as that of a variable declared in the same location. You can
specify scope in any of the following ways:
To create a constant that exists only within a procedure, declare it within that procedure.
To create a constant available to all procedures within a class, but not to any code outside that
module, declare it in the declarations section of the class.
To create a constant that is available to all members of an assembly, but not to outside clients
of the assembly, declare it using the Friend keyword in the declarations section of the class.
To create a constant available throughout the application, declare it using the Public keyword
in the declarations section the class.
A compile-time constant is computed at the time the code is compiled, while a run-time constant
can only be computed while the application is running. A compile-time constant will have the same
value each time an application runs, while a run-time constant may change each time.
The following table shows how constants may be declared and the location of their declaration
affects the scope:
Keyword Where
General Declarations General Sub or Function
Used to Declared
Section of a Form Declarations procedure of a
Declare the
(.frm) Module Section of a Form or
Constant:
Standard (.bas) Standard
Module Module
Const module-level scope module-level local-level
scope scope
In the above outline, Dim is the keyword which indicates to Visual Basic that a variable is being
declared. variableName is the name assigned to the variable. Try to use a descriptive variable
name and prefix the name with something which indicates the variable type. For example, when
declaring a String variable prefix the name with str (e.g. strFirstName). The As keyword
precedes the declaration of the variable type (String, Date, Integer etc).
Visual Basic variables may be initialized either during the declaration, or after the declaration.
Unless there is a good reason to do otherwise, it is recommended that variables be initialized
during the declaration.
Initialization is performed using the Visual Basic assignment operator (=). To initialize a single
variable when it is declared:
Dim intInterestRate As Integer=5
Module Level Scope
When a variable or constant is declared outside of any procedures or code structures in a Module
it is deemed to have module level scope. This means that the variable or constant is visible to all
Visual Basic code contained in the same module, regardless of whether that code is located in a
procedure or not. There is a section at the top of each module called the Declarations Section for
this purpose. The Declaration section is located above all procedures and code in a module
Global Scope
When a variable or constant is declared as global it is visible to all procedures and modules that
comprise the application. Global variables and constants, as with Module level variables, must be
declared outside of any procedures in the Declarations section and must use the Public keyword.
The syntax for declaring a global variable is as follows:
Public variableName As dataType
In VB, you can also use a set of functions that explicitly convert (or "cast") one type of data to
another. The set of functions that enable you to do this all begin with the letter "C": CBool,
CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, and CVar. In addition, two older
functions, Val and Str, enable you to convert from a string to a number and from a number to a
string, respectively. Each function is described below:
CBool takes any valid expression and converts it to Boolean. Values of zero convert to False, all
others to True. If the expression is String, it must be a string that can be converted to a number
(like "123"). The strings "True" and "False" will also work; any other string will result in an
error.
ARRAYS
An array is a consecutive group of memory locations that all have the same name and the same
type. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger size
than required. We can declare an array of any of the basic data types including variant, user-
defined types and object variables. The individual elements of an array are all of the same data
type.
Declaring Arrays
Arrays are declared in the same manner as other variables (i.e., using the keywords "Dim",
"Private", "Public", etc.), except that the array bounds are coded in parentheses following the
variable name (if a fixed-length array is being declared) or an empty pair of parentheses follow
the variable name (if a variable-length, or dynamic array is being declared).
For fixed-length arrays, you must specify the upper bound of the array; you can
optionally specify the lower bound. By default, the lower bound is 0 (however, see the note on
the "Option Base" statement further below). For variable-length arrays, you do not specify any
bounds; you just code an empty set of parentheses.
Arrays can have up to 60 dimensions (although it is rare that you would have more than
three dimensions; one or two is the norm).
The syntax for declaring an array is:
[Dim|Private|Public|Static|Global] arrayname([lowerbound To] upperbound[,
Parts
Preserve
Optional. Modifier used to preserve the data in the existing array when you change the size of
only the last dimension.
name
Required. Name of the array variable. See Declared Element Names.
boundlist
Required. List of bounds of each dimension of the redefined array.
COMMENTS
The previous listing introduced a new syntax element: the comment. A comment is a line that is
NOT source code. Instead, it is there as guidance to the person reading the code. When
programmers write programs, they usually (or at least they should) add comments describing
large sections of code that could potentially be confusing. Comments begin with an apostrophe
("'") and end with a new line. Everything that you type after the apostrophe is ignored by Visual
Basic, which is the entire point of comments. You will see comments in all future listings
describingnewconceptsandsyntax.
CONTROL STATEMENTS:
Do-Loops
The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple:
Do
(Statements)
Loop
Exit Do
So we clearly need some way to escape from the Do-Loop. You could, of course, simply End the
program once you have calculated enough values, but what if you still need to perform tasks
after you're done calculating? The answer is to use the Exit Do statement. Whenever your
program reaches an Exit Do statement within a loop, it will exit the current loop.
Do Until
As an alternative approach to nesting an If-Statement inside the loop, and invoking Exit Do once
we're done looping, Visual Basic provides a Do Until statement. Its syntax is the following:
Do
(statements)
Loop Until (Expression)
(Expression) can be any legal logical expression that we wish to evaluate to determine whether
or not to exit the loop. Each time the program reaches Loop it will evaluate this expression. If the
expression is True, it will exit the loop for us, but otherwise it will continue looping..
Do While
In the place of Do Until, you can also use Do While. Its syntax is the following:
DoWhile(Expression)
(statements)
Loop
(Expression) can be any legal logical expression that we wish to evaluate to determine whether
or not to exit the loop. Each time the program reaches Loop it will verify that this expression is
True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is
True, it now exits only once this expression is false.
For-Next Loops
In situations where you merely want to run the loop a predefined number of times, it can become
quite tiresome to have to create and manage a counter for each loop, which is why we also have
something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to
count from one number to another each time through the loop, and to exit once the counter has
reached its upper limit. The syntax is as follow:
Dim I As Integer
Term Definition
expressionlist Required in a Case statement. List of expression clauses representing match values forteste
are separated by commas. Each clause can take one of the following forms:
expression1 To expression2
[ Is ] comparisonoperator expression
expression
Use the To keyword to specify the boundaries of a range of match values fortestexpression.
than or equal to the value ofexpression2.
Use the Is keyword with a comparison operator (=, <>, <, <=, >, or >=) to specify
for testexpression. If the Is keyword is not supplied, it is automatically inserted before comp
The form specifying only expression is treated as a special case of the Is form wherecompar
form is evaluated as testexpression =expression.
The expressions in expressionlist can be of any data type, provided they are implicitly conve
the appropriate comparisonoperator is valid for the two types it is being used with.
statements Optional. One or more statements following Case that run if testexpression matches any clau
elsestatements Optional. One or more statements following Case Else that run if testexpression does not m
any of the Case statements.
End Select Terminates the definition of the Select...Case construction.
GOTO Statement:
The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is −
GoTo label
Flow Diagram
STRING:
Strings are enclosed in double quotes ( " " )
Syntax
Visual Basic has many built-in functions for manipulating text and carrying out mathematical
operations, as well as the ability to format data in both standard and user-defined styles. We start
by looking at two functions that are both frequently used and at the same time relatively easy to
get to grips with - the MsgBox() function and the InputBox() function. We will then look at some
of the more commonly-used string-handling and math functions, and the ways in which
numerical, date and time values can be represented.
The MsgBox() function displays a message in a pop-up message box (no surprises there!). The
user is expected to respond by clicking on a button in order to be able to continue. The format of
the statement used to invoke a message box is as follows:
The prompt parameter is a string value (either a string literal or a string variable) that supplies
the message to be displayed. The styleVal parameter is either an integer style value from 0 to 5,
or a named constant that can be used instead of the corresponding integer value, that determines
which command buttons will appear on the message box. The title parameter is another string
literal or string variable that supplies the title for the message box.
vbYesNo Yes, No
The returnVal value returned by the MsgBox() function is an integer value that indicates which
button the user has clicked in response to the message box being displayed. The possible return
values together with the named constants that may be used in their stead, are listed in the table
below.
1 vbOk OK
2 vbCancel Cancel
3 vbAbort Abort
Message Box Return Values
Return value Named constant Button clicked
4 vbRetry Retry
5 vbIgnore Ignore
6 vbYes Yes
7 vbNo No
The message box can be further embellished by the inclusion of an icon that will appear beside
the message. In Visual Basic, there are four icons available. The icon is included either by
incrementing the style value by a fixed constant value, or by the inclusion of a second named
constant (see table below).
32 vbQuestion
48 vbExclamation
64 vbInformation
The following statements would produce exactly the same message box, and are essentially
equivalent to one another:
The InputBox() function displays a pop-up input box into which the user can type a message. The
user is expected to enter their message, then click on a button ("Cancel" or "OK") in order to
continue. The format of the statement used to invoke an input box is as follows:
The returnString returned by the InputBox() function is the text entered by the user. The prompt
parameter is a text string (either a string literal or a string variable) that prompts the user to enter
some information. The title parameter is another string literal or string variable that supplies the
title for the input box. The defaultText parameter can be used to enter default content in the input
box (although it would probably be left blank in most cases). The xpos and ypos parameters
specify the x and y coordinates for the input box on screen.
String functions
String Functions
Function Description
Returns n characters from the text string referred to by str, starting
Mid (str, pos, n) at character position pos.
Microsoft.VisualBasic.left Returns the n left-most characters from the text string referred to
(str, n) by str.
Microsoft.VisualBasic.right Returns the n right-most characters from the text string referred to
(str, n) by str.
Removes the white space (if any) at either end of the text string
Trim (str) referred to by str, and returns the result.
Removes the white space (if any) at the left-hand end of the text
LTrim (str) string referred to by str, and returns the result.
Removes the white space (if any) at the right-hand end of the text
RTrim (str) string referred to by str, and returns the result.
Looks for an occurrence of the substring str2 within the string
InStr (n, str1, str2) str1, starting at character position n. If successful, the function
returns the character position at which the substring is found (or
zero if the substring cannot be found).
Converts the string referred to by str to all upper-case characters,
UCase (str) and returns the result.
Converts the string referred to by str to all lower-case characters,
LCase (str) and returns the result.
Returns the ASCII character corresponding to the 8-bit character
Chr (charCode)
Maths functions
Maths Functions
Function Description
Math.Sqrt (n) Returns the square root
of a number, n. Math.Abs (n) Returns
the absolute value of a number, n.
Returns the exponential value of a number, n – i.e. e n.
Math.Exp (n) Note: e = 2.71828182
Fix (n) Returns the integer part of a floating point number, n.
Returns the integer part of a floating point number, n, for Int (n)
positive numbers, or the next smallest integer value for negative numbers.
Math.Log (n) Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value
between 0 and 1. Round (n,m) Rounds a number, n,
up (or down) to m decimal places.
Formatting numbers
The Format() function allows you to specify precisely how numeric values
are displayed. The function is used as follows:
The first argument (n) is the number to be formatted. The value selected for the
second argument ("styleArg") will determine how the number is displayed. The
possible values are described in the table below (note that a user-defined value
for "styleArg" can also be used).
The Format() function can also be used to specify how date and time values are
displayed. The function is used as follows:
The first argument (Date) is the date to be formatted (note that if you are
using the current date, the Now function can be used as the argument. The
value selected for the second argument ("styleArg") will determine how the
date value is displayed. The possible values are described in the table below
(note that a user-defined value for "styleArg" can also be used).